我对使用 std::map
有一些问题:
Is using an
enum
as the key instd::map
a 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::map
class, 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?