重载 std::string 小于 C++ 中的运算符
overload std::string less than operator in c++
我想使用 map<string, int>
来存储字符串及其出现。
由于要求,我必须以与授予的词典顺序不同的顺序为 std::string 重载“<”运算符。我用的是免费功能,如下
bool operator<(const string& a, const string& b) {
int mini = min (a.length(), b.length());
for(int i=0; i < mini; ++i){
if (a[i] < b[i])
return true;
}
if (a.length() <= b.length()) return false;
return true;
}
但是,它不会被调用。字典顺序被调用。
这是正确的方法吗?
不,那不是正确的方法。
您应该定义一个自定义仿函数来进行您需要的比较。在创建地图时使用它。
struct MyCustomFunctor
{
bool operator()(const string& a, const string& b) { /* Add the details */ }
};
然后,使用以下方法创建地图:
map<string, int, MyCustomFunctor> myMap;
如果您能够使用支持 C++11 的编译器,那么您可以使用 lambda 函数来完成这项工作,而不必创建 class.
auto lambda = [](const string& a, const string& b) -> bool {return (a < b);};
map<string, int, decltype(lambda)> myMap(lambda);
当您将 map
与自定义比较函数一起使用时,您必须记住对 map::begin()
、map::end()
、map::find()
等的调用 return 一个迭代器,其类型包括自定义比较函数。使用 auto
是创建作为 map
.
迭代器的变量的最佳方法
auto it = myMap.begin();
auto it = myMap.find("some key");
我想使用 map<string, int>
来存储字符串及其出现。
由于要求,我必须以与授予的词典顺序不同的顺序为 std::string 重载“<”运算符。我用的是免费功能,如下
bool operator<(const string& a, const string& b) {
int mini = min (a.length(), b.length());
for(int i=0; i < mini; ++i){
if (a[i] < b[i])
return true;
}
if (a.length() <= b.length()) return false;
return true;
}
但是,它不会被调用。字典顺序被调用。 这是正确的方法吗?
不,那不是正确的方法。
您应该定义一个自定义仿函数来进行您需要的比较。在创建地图时使用它。
struct MyCustomFunctor
{
bool operator()(const string& a, const string& b) { /* Add the details */ }
};
然后,使用以下方法创建地图:
map<string, int, MyCustomFunctor> myMap;
如果您能够使用支持 C++11 的编译器,那么您可以使用 lambda 函数来完成这项工作,而不必创建 class.
auto lambda = [](const string& a, const string& b) -> bool {return (a < b);};
map<string, int, decltype(lambda)> myMap(lambda);
当您将 map
与自定义比较函数一起使用时,您必须记住对 map::begin()
、map::end()
、map::find()
等的调用 return 一个迭代器,其类型包括自定义比较函数。使用 auto
是创建作为 map
.
auto it = myMap.begin();
auto it = myMap.find("some key");