Possible duplicate:
Is it better to use map :: insert in STL maps than []?
I was wondering when I insert an element into the map, what is the recommended way. Should I
map[key] = value;
or
map.insert(std::pair<key_type, value_type>(key, value));
I did the following quick test:
#include <map> #include <string> #include <iostream> class Food { public: Food(const std::string& name) : name(name) { std::cout << "constructor with string parameter" << std::endl; } Food(const Food& f) : name(f.name) { std::cout << "copy" << std::endl; } Food& operator=(const Food& f) { name = f.name; std::cout << "=" << std::endl; return *this; } Food() { std::cout << "default" << std::endl; } std::string name; }; int main() { std::map<std::string, Food> m0; /* 1) constructor with string parameter 2) copy 3) copy 4) copy */ m0.insert(std::pair<std::string, Food>("Key", Food("Ice Cream"))); /* 1) constructor with string parameter 2) default 3) copy 4) copy 5) = */ // If we do not provide default constructor. // C2512: 'Food::Food' : no appropriate default constructor available m0["Key"] = Food("Ice Cream"); }
- I understand, using the
insert member function, a smaller function call will be involved. So insert recommended method? - Why is a default constructor needed when the
map[key] = value method is used?
I know that insert does not overwrite a pair of existence values, but map[key] = value does. However, is this the only factor that I take into account when I try to choose from both?
What about
- Performance
- Default Constructor Availability
- ???
c ++ stl stdmap
Cheok Yan Cheng Aug 05 2018-11-11T00: 00Z
source share