If you want to update the existing map element, operator[] is better, but if you want to add a new element, insert has an advantage.
More efficient "Add or update" functions (functions in the book I plucked out ~)
Template<typename Maptype,
TypeName Keyargtype,
TypeName Valueargtype>
TypeName Maptype::iterator
Efficientaddorupdate (maptype& m,
Const keyargtype& K,
Const valueargtype& v)
{
TypeName Maptype::iterator lb = M.lower_bound (k);
if (lb! = M.end () &&! ( M.key_comp () (k, Lb->first)) {//its key is equivalent to K ...
Lb->second = v; Update the value of this pair
return lb;
}
else {
typedef typename MAPTYPE::VALUE_TYPE MVT;
Return M.insert (LB, MVT (k, v)); Why add the LB parameter to the Insert method, please refer to the @3
}
}
When using map::operator[] inserted element does not exist, its efficiency is very low, so there is the above function, it specifically how low method here does not say, look at the following key points:
@1 Lower_bound
Prototype: iterator Lower_bound (const key_type& x);
Returns a iterator that points to the first element in a container that is not less than (greater than or equal to) x. Note that the elements in the map are stored in the order of key.
@2 Key_comp
Key_comp is a member of map, C.key_comp () (x, Y) returns true only if x precedes y in the sort order of C
@3 about Map::insert
Specifying an position parameter for the insert makes it significantly more efficient, which is why the find does not find the returned iterator to Map::end by using Lower_bound lookup instead of the find lookup.
(EXT) Effective STL clause 24: When it comes to efficiency, you should choose between map::operator[] and Map::insert carefully.