C++ 对映射使用自己的比较器运算符()。如果找不到密钥,则给出错误
我已尝试实现自己的运算符并在map中使用,代码如下所示:C++ 对映射使用自己的比较器运算符()。如果找不到密钥,则给出错误,c++,map,struct,operator-overloading,C++,Map,Struct,Operator Overloading,我已尝试实现自己的运算符并在map中使用,代码如下所示: #include <iostream> #include <map> #include <string> using namespace std; struct keyInfo { string Key1; string Key2; /*bool keyInfo::operator()(keyInfo const& Left,keyInfo const& Right
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct keyInfo
{
string Key1;
string Key2;
/*bool keyInfo::operator()(keyInfo const& Left,keyInfo const& Right) const{
return ((Left.Key1<Right.Key1)&&(Left.Key2<Right.Key2));
}*/
};
struct LessComparer{
bool operator()(keyInfo const& Left,keyInfo const& Right) const{
return !(Left.Key1==Right.Key1 && Left.Key2==Right.Key2);
}
};
struct valueInfo
{
int value1;
int value2;
int value3;
valueInfo(const int A,const int B,const int C) :
value1(A),value2(B),value3(C) {}
};
typedef std::map<keyInfo, valueInfo, LessComparer> MapTYPE;
int main()
{
MapTYPE TMap;
keyInfo K;
K.Key1="main";
K.Key2="i";
valueInfo V(-2,-3322,9000);
TMap.insert(MapTYPE::value_type(K,V));
MapTYPE::iterator It1=TMap.find(K);
It1=TMap.find(K);
if(It1!=TMap.end())
std::cout<<"Success(K): "<<It1->second.value2<<std::endl;
keyInfo E;
E.Key1="main";
E.Key2="j";
//TMap.insert(std::pair<keyInfo,valueInfo>(E,V));
MapTYPE::iterator It2=TMap.find(E);
if (It2!=TMap.end())
std::cout<<"Success(E): "<<(It2->second).value3<<std::endl;
cin.get();
return 0;
}
return (Left.key1 < Right.key1) ||
(!(Left.key1 > Right.key1) && (Left.key1 < Right.key1));
这里我使用运算符返回0,如果左右键的Key1和Key2相等。我认为这与map::less的工作方式相同,我的意思是,只有满足相等条件时,它才会返回false
它在第一种情况下工作正常,即TMap.findK中找到相同的密钥。但在第二种情况(即TMap.findE)的调用过程中,会弹出一个错误,显示:
"Debug assertion failed"
Expression: Invalid operator <
比较运算符必须定义严格的弱顺序。一般来说,您可以通过字典比较为可比较类型的化合物编写这样的比较:
define "(a1, b1) < (a2, b2)" if and only if
(a1 < a2) OR (a1 == a2 AND b1 < b2)
通过这种方式,您可以仅使用现有的在任何类型元组上定义字典顺序。比较运算符必须定义严格的弱顺序。一般来说,您可以通过字典比较为可比较类型的化合物编写这样的比较:
define "(a1, b1) < (a2, b2)" if and only if
(a1 < a2) OR (a1 == a2 AND b1 < b2)
通过这种方式,您可以仅使用现有的