C++标准库利用仿函数为map提供排序规则

本文介绍了一个C++程序示例,展示了如何定义并使用一个名为RuntimeStringCmp的类来实现字符串的正常比较及忽略大小写的比较,并将这种比较逻辑应用于标准模板库(map)中,以展示不同比较方式下数据的排序效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <iomanip>
#include <map>
#include <string>
#include <altorithm>
using namespace std;
class RuntimeStringCmp{
    public :
    enum cmp_mode{normal , nocase};

    private:
    const cmp_mode mode;
    static bool nocase_compare(char c1 , char c2)
    {
        return toupper(c1) < toupper(c2);
    }
    public:
    RuntimeSringCmp(cmp_mode m = normal) : mode(m)
    {
    }
    bool operator()(const string & s1 , const string &s2) const{
        if(mode == normal){
            return s1 < s2;
        }else{
            return lexicographical_compare(s1.begin() , s1.end() , 
                                            s2.begin() , s2.end(),
                                            nocase_compare());
        }
    }

}
typedef map<string , string , RuntimeStringCmp> StringStringMap;
void fillAndPrint(StringStringMap & coll);
int main()
{
    StringStringMap coll1;
    fillAndPrint(coll1);
    RuntimeStringCmp ignorecase(RuntimeSringCmp::nocase);
    StringStringMap coll2(ignorecase);
    fillAndPrint(coll2);
}
void fillAndPrint(StirngStringMap & coll)
{
    coll["Deutschland"] = "Germany";
    coll["deutsch"] = "German";
    coll["Haken"] = "snag";
    coll["arbeiten"] = "work";

    //print elements
    StringStringMap::iterator pos;
    cout.setf(ios::left , ios::adjustfield);
    for (pos = coll.begin(); pos != coll.end() ;++pos){
        cout << setw(15) <<pos->first.c_str() << " " << pos->second << endl;
    }
    cout << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值