STL中关联式容器的compare
程序员文章站
2022-04-01 12:19:17
关联式容器排序准则(执行期指定)#ifndef _COMPARE_H#define _COMPARE_H#include#include#include#includeclass RuntimeStringCmp{public:enum cmp_mode{normal, nocase};RuntimeStringCmp(const cmp_m...
关联式容器排序准则(执行期指定)
#ifndef _COMPARE_H
#define _COMPARE_H
#include<algorithm>
#include<string>
#include<iostream>
#include<iomanip>
class RuntimeStringCmp
{
public:
enum cmp_mode
{
normal, nocase
};
RuntimeStringCmp(const cmp_mode& m = normal) :mode(m) {}
bool operator()(const std::string& s1, const std::string& s2)const
{
if (mode == normal)
return s1 < s2;
else
return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), nocase_compare);
}
private:
const cmp_mode mode;
static bool nocase_compare(char C1, char C2)
{
return toupper(C1) < toupper(C2);
}
};
typedef std::map<std::string, std::string, RuntimeStringCmp> StringStringMap;
template <typename T>
void print(T& maps)
{
std::cout.setf(std::ios::left, std::ios::adjustfield);
typedef T::const_iterator pos;
for (pos iter = maps.begin(); iter != maps.end(); ++iter)
{
std::cout << std::setw(15) << iter->first << " " << iter->second << std::endl;
}
std::cout << std::endl;
}
void fillAndPrint(StringStringMap& coll)
{
coll["Deutschland"] = "Germay";
coll["deutsch"] = "German";
coll["Haken"] = "snag";
coll["arbeiten"] = "work";
coll["Hund"] = "dog";
coll["gehen"] = "go";
coll["Unternehmen"] = "enterprise";
coll["unternehmen"] = "undertake";
coll["gehen"] = "walk";
coll["Hestatter"] = "undertaker";
print(coll);
}
#endif // !_COMPARE_H
测试
#include<map>
#include<iostream>
#include"compare.h"
int main()
{
StringStringMap colll;
fillAndPrint(colll);
RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);
StringStringMap coll2(ignorecase);
fillAndPrint(coll2);
std::cout << "Hello World!" << std::endl;
}
运行结果
分析
RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);
///<在运行程序期间决定关联式容器的排序准则,“忽略大小写”
StringStringMap coll2(ignorecase);
注意
如果将比较函数的operator函数对象定义为以下:
bool operator()(const std::string& s1, const std::string& s2)
{
if (mode == normal)
return s1 < s2;
else
return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), nocase_compare);
}
会出现这样的错误:
分析:出现这样的原因跟关联式容器map的“key”是常数类型有关,函数对象不能修改“key”
所以,必须将函数对象定义为const函数对象:
bool operator()(const std::string& s1, const std::string& s2)const
{
if (mode == normal)
return s1 < s2;
else
return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), nocase_compare);
}
本文地址:https://blog.csdn.net/weixin_44312010/article/details/107581087