Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance cost of comparing two C++ iterators

In general, what is the performance cost of an equality comparison between two STL container iterators? I'm only talking about defined operations; that is, comparing two iterators referring to the same object.

My specific use-case is that I have a std::map that could potentially have very large elements, lots of elements, or both. If an equality comparison between two iterators over such a map have hidden penalties that I'm not aware of, it could impact the performance of my code.

like image 302
George Hilliard Avatar asked Feb 03 '26 17:02

George Hilliard


1 Answers

Generally, the performance of comparing two iterators depends on the implementation of the STL.

However, concerning the time complexity, the C++ standard imposes the restriction that comparison of input iterators (and thus forward iterators, bidirectional iterators and random access iterators) takes amortized constant time. Particularly, this means for an std::map<std::string, int>, that its iterators cannot be compared by comparing the keys for equality, because that would be linear with respect to the length of the key.

like image 95
Oswald Avatar answered Feb 06 '26 07:02

Oswald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!