Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For how long the iterator returned by std::set.find() lives?

Tags:

c++

set

stl

stdset

I need to keep track of std::set element by saving the iterator returned by set.find().

My questions is does insertion and removing other elements invalidates the obtained iterator? From a simple test I did I can see it is not, but I'd like to ensure this feature is by design.

like image 495
jackhab Avatar asked Mar 02 '10 16:03

jackhab


People also ask

What is the time complexity of set find?

Time Complexity: The time complexity of set_name. find( key ) is O( log N ). As the elements are stored in a sorted manner by default.

Is std :: find slow?

std::equal_range on bidirectional iterators is extremely slow, because it has to walk step by step through the range. The std::set. find method, on the other hand, uses the tree structure of std::set to find the element really fast. It can, basically, get midpoints of a range really fast.

What does set find return?

C++ set find() C++ set find() function is used to find an element with the given value val. If it finds the element then it returns an iterator pointing to the element otherwise, it returns an iterator pointing to the end of the set i.e. set::end().

What is Find function in C++?

C++ Algorithm Library - find() Function The C++ function std::algorithm::find() finds the first occurrence of the element. It uses operator = for comparison.


1 Answers

It never invalidates iterators or pointers/references to the elements. Only if you remove the element itself does the iterator or pointer/reference become invalid.

23.1.2/8:

The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

like image 158
Johannes Schaub - litb Avatar answered Nov 10 '22 17:11

Johannes Schaub - litb