map<string, int> a; string s("asd"); int i=1; a.insert(map::make_value(s,i)); What is the difference between a[s] and (a.find(s))->second ? Is it possible instead
a.insert(map::make_value(s,i)); use
a[s]=i; operator[] adds a key-value pair to the map if there is no pair with the specified key. find does not add anything, but simply returns an iterator that provides access to the desired pair. As for the second part of the question,
a[s]=i; then no one forbids you to write like that. Personally, I prefer to add pairs to the map explicitly.
PS: if the order of the keys is not important, use a faster unordered_map .
The answer to the second question follows from the answer to the first. In the absence of a key value via operator [], a new item will be created automatically. And in this case find will return an after-end iterator, with all the consequences when trying to access via pair-> second.
(a.find (s)) -> second
Wait for troubles. Before turning to second, be sure to check the validity of the iterator obtained from the find method.
map<string, int>::iterator it_found = a.find(s); if(it_found != a.end()) { it_found->second; } Source: https://ru.stackoverflow.com/questions/337100/
All Articles
(a.find(s))->secondabout the difference betweena[s]and(a.find(s))->secondwhen contacting ... for example, here’scout << a[s]as I understand it, there can be an error if an element with such a key will not be in themap, and it is necessary to checkif ( a.find(s) != a.end() ) { ...? - who-e