What are the advantages/disadvantages in using std::map's interator or using [] operator?
For example:
Code:map<char,int> ht;
cout<<ht['s']<<endl;
ht['s']++;
map<char,int>::iterator it = ht.find('s');
cout<<it->second<<endl;
What are the advantages/disadvantages in using std::map's interator or using [] operator?
For example:
Code:map<char,int> ht;
cout<<ht['s']<<endl;
ht['s']++;
map<char,int>::iterator it = ht.find('s');
cout<<it->second<<endl;
The [] operator adds a blank entry to the map if it does not exist. If the find() function does not find the entry it simply points to the end of the map. (the map is not modified in any way)
Not sure if that answered your question or not. I don't know if cout << foo[6]; is undefined behavior or if that is valid code. i.e.Code:map<int, int> foo;
foo[5] = 5; // Add an entry with key 5 and value 5.
int a = foo[5]; // Retrieve value at key 5 (which is 5)
map<int, int>::iterator f = foo.find(5); // Returns a valid iterator as key 5 exists.
map<int, int>::iterator g = foo.find(6); // Returns an "invalid" iterator as key 6 does not exist. No modifications to the map are made.
cout << foo[6]; // Output value at key #6.. wait key #6 does not exist.. Adds key #6 to the map and sets to zero and outputs zero. So now the map has grown.
Code:struct foo{
int b;
DWORD d;
};
map<int. foo> mapOne;
mapOne[5]; // Add a new entry with key 5. Does the value struct foo get initialized to zero? I didn't bother checking.
>> Does the value struct foo get initialized to zero?
Yes. If you use operator[] and the key does not exist then a value is created and default initialized.
I think that is the biggest difference between the iterator and the operator[].
And find has a const version which allow to express (and assure) that your algorithm will not change the map.