Using char * as a key in std :: map how it works

This question relates directly to using char as a key in stdmap .

I understand what the comparison function passed, and why it is required for char * types as a key. However, I'm not sure how the update really works.

I am wondering when you update a key. How std::map knows how to compare the equality between const char * , cmp_str , only indicates the map into which the keys are inserted into the tree.

I worked a bit with the stl_tree.h code ( pulled from here ), but could not find much. My only guess is that he is doing a direct memory comparison.

I am wondering how the underling class stl_tree handles this situation, or if it does not handle it correctly all the time, which extreme register is interrupted?

the code

 #include <map> #include <iostream> #include <cstring> struct cmp_str { bool operator()(char const *a, char const *b) { return std::strcmp(a, b) < 0; } }; int main ( int argc, char ** argv ) { std::map<const char*, int, cmp_str> map; map["aa"] = 1; map["ca"] = 2; map["ea"] = 3; map["ba"] = 4; map["ba"] = 5; map["bb"] = 6; map["ba"] = 7; std::map<const char*, int, cmp_str>::iterator it = map.begin(); for (; it != map.end(); it++ ) { std::cout << (*it).first << ": " << (*it).second << std::endl; } return 0; } 

Exit

 aa: 1 ba: 7 bb: 6 ca: 2 ea: 3 
+7
source share
2 answers

Sorted containers use equivalence classes: two values a and b are considered equivalent if none is less than the other !(a < b) && !(b < a) or, if you insist on entries using a binary predicate !pred(a, b) && !pred(b, a) .

Note that you need the pointers to appear on your map: if the pointers go out of scope, you will get strange results. Of course, string literals remain valid throughout the life of the program.

+6
source

Well, cmp_str can be used to search for identical keys. If both cmp_str::operator(x,y) and cmp_str::operator(y,x) return false , you have found a duplicate key. There really is not much more.

+6
source