代碼在C++:使用struct作爲KEY和VALUE來繪製地圖。找到()操作給錯誤
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct keyInfo
{
string Key1;
string Key2;
bool keyInfo::operator <(keyInfo &A) const
{ return ((this->Key1<A.Key1)&&(this->Key2<A.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> 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;
}
當我編譯此代碼它給我的錯誤:
error C2679: binary '<' : no operator found which takes a right-hand operand of type 'const keyInfo1' (or there is no acceptable conversion)
請讓我知道我要去哪裏錯了嗎? 任何幫助是高度讚賞。 謝謝。
我試圖實現自己的運營商,在地圖<>使用,代碼如下:
#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;
}
這裏我使用的是運營商()來當且僅當左,右兩個鍵1和鍵2返回0是平等的。我認爲這與map :: less的作用是一樣的,我的意思是隻有滿足條件時才返回false。
它在第一種情況下工作正常,即找到相同密鑰的TMap.find(K)。但是在第二種情況下,即TMap.find(E)通話過程中它會彈出一個錯誤說:
"Debug assertion failed"
Expression: Invalid operator <
除了使參數'const',你也應該考慮你是否真的希望兩個鍵都小於彼此。如果'Key1'等於'A.Key1',會發生什麼? – 2012-03-10 14:20:10