"Effective STL" clause 24: When it comes to efficiency, you should choose between map::operator[] and Map::insert carefully.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.