简体   繁体   中英

C++ map::find or map::iterator which is more efficient w.r.t complexity

As we know map::find returns an iterator pointing to location where it find the location of the key. Also as its a binary search operation the complexity is O(logn). So it seems internally it maintain an iterator and that will be return on success. So which one is more efficient find or iterator as I think both will provide the same complexity at run time (I may be incorrect). So can you please suggest where to use find and where to use iterator. As in one of the implementation I need to look into map for a particular keys (as it can contain N keys out of which we are interested in m keys only). So whether find will be more efficient or iterator. Also what will be good way to handle find failure case as I don't want to put much if else case in code which will increase the complexity.

I'm not entirely sure what you mean but using std::map<...>::find() will be more efficient than than using std::lower_bound() on map's iterators: the binary search on the internal tree just navigates the tree and has O(log(n)) performance with n being the size of the map. std::lower_bound() would also do a binary search but it would need to use operator++() and/or operator--() to move the iterator. Thus, it would have O(n) performance. I think it shouldn't even compile but I'm not entirely sure whether it doesn't compile.

For a start they do two different things. Secondly it depends on the implementation.

As a rule of thumb: if you can choose between a generic algorithm ( std::find here) and a container specific algorithm of the same name ( std::map<...>::find here), then use the container specific one.

Nobody would have bothered implementing a container specific one if it were not more efficient than the generic version, it would have been a loss of time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM