我有带有'
class CustomKey;
typedef map<CustomKey, int> KeyValueMap;
class CustomKey {
public:
string key1;
int key2;
int key3;
bool operator < (const CustomKey & rhs) const {
return ((key1 < rhs.key1) || ((key1 == rhs.key1) && (key2 < rhs.key2)) || ((key2 == rhs.key2) && (key3 < rhs.key3)));
}
void display() const {
cout << key1 << ":" << key2 <<":" << key3;
}
};
我能够添加并显示下面的所有五个键。
void addDataToMap(KeyValueMap & valueMap) {
CustomKey key1 = {"one", 100, 50};
valueMap[key1] = 1;
CustomKey key2 = {"two", 200, 150};
valueMap[key2] = 2;
CustomKey key3 = {"moreabc", 100, 100};
valueMap[key3] = 27;
CustomKey key4 = {"less", 100, 150};
valueMap[key4] = 30;
CustomKey key5 = {"morexyz", 100, 101};
valueMap[key5] = 33;
}
void displayMap(const KeyValueMap & valueMap) {
KeyValueMap::const_iterator iter = valueMap.begin();
while(iter != valueMap.end()) {
iter->first.display();
cout << " => " << iter->second << endl;
iter++;
}
}
但是奇怪的是,在以下情况下搜索失败。 addDataToMap中添加的不同组合具有不同的结果。
void searchMap(const KeyValueMap & valueMap) {
CustomKey key3 = {"morexyz", 100, 101};
cout << "MapSize = " << valueMap.size() << endl;
KeyValueMap::const_iterator iter = valueMap.find(key3);
if(iter == valueMap.end()) {
cout << "NotFound" << endl;
return;
}
cout << iter->second << endl;
}
int main() {
KeyValueMap valueMap;
addDataToMap(valueMap);
displayMap(valueMap);
searchMap(valueMap);
cout << endl;
return 0;
}
输出:-
one:100:50 => 1
moreabc:100:100 => 27
morexyz:100:101 => 33
less:100:150 => 30
two:200:150 => 2
MapSize = 5
NotFound
我相信,在'
[尝试考虑key1 > rhs.key1
和key2 == rhs.key2
和key3 < rhs.key3
的情况,operator <
将返回不期望的true
。
您可以将(key1 == rhs.key1)
保留在[C0]的最后operator ||
中。例如
operator <
bool operator < (const CustomKey & rhs) const {
return ((key1 < rhs.key1) ||
((key1 == rhs.key1) && (key2 < rhs.key2)) ||
((key1 == rhs.key1) && (key2 == rhs.key2) && (key3 < rhs.key3)));
}