I am trying to build a map with a custom comparator, however, something that I can not figure it out goes wrong, being unable to add item to the map (specifically, can only add the first item)
struct byKey { bool operator () ( const Key &key1, const Key &key2) const { return key1.keytoInt() < key2.keytoInt(); } }; where Key class has a private char[5], like
char[0]=1, char[1]=2, char[3]=13, char[4]=20, char[5]=28 there is a matching going that ensures all the character in char digit[5] (is less than 32) and can be converted to a character.like char=0, it will search a table, find a character like A
I use a method in Key to covert it to int, then compare with int
int Key :: keytoInt() const{ int sum; sum=atoi(digit); return sum; } I build a table of map with key and value both as Key type, however, when trying to test it, I can not add items to the table, I am not sure where goes wrong.
No compile error, however, logically, even though I have inserted into the map three times, the map.size() shows there is only one
map<Key,Key,byKey> firstmap; map<Key,Key>::iterator it; firstmap.insert(pair<Key,Key>(base,stepguess)); firstmap.insert(pair<Key,Key>(stepguess,base)); firstmap[stepguess]=base; cout << "wait"; cout << "mymap.size() is " << firstmap.size() << '\n';
std::stringas the map key. No more calls toatoiwould be required, and thestruct byKeygoes away. Also remember that the map can be sorted in ascending or descending order by using theless <T>orgreater<T>in the third parameter of the map instance declaration.