I have some questions on using std::map:
-
Is using an
enumas the key instd::mapa good practice? Consider the following code:enum Shape{ Circle, Rectangle }; int main(int argc, char* argv[]) { std::map<Shape,std::string> strMap; // strMap.insert(Shape::Circle,'Circle'); // This will not compile strMap[Shape::Circle] = 'Circle'; // But this will work return 0; } -
In the above example, why is the call to
insert()generating a compiler error while the overloaded[]operator works correctly? Which of these methods is recommended for inserting items into astd::map? -
I understand that when the
find()method is used on thestd::mapclass, it is not doing a sequential search in the container but doing some logarithmic search which will be much faster than sequential search. Is this understanding correct?
std::vectorwith O(1) access is even better.insertmust be used like this:mapVar.insert(make_pair(key, value));See also cppreference.com.std::maphas O(log(n)) lookup, as guaranteed by the standard, and this is faster than O(n) if n is sufficiently high.