shole
shole

Reputation: 4084

Can iterator points to specific position instead of value in STL set?

set<int> st;
set<int>::iterator it;

for(int i=10; i<20;i++)
    st.insert(i);

it = st.begin();
advance(it, 4); // it points to the 5th element which is 14

for(int i=0; i<10; i++)
    st.insert(i);

// At this point where does it points to? The 5th element which is 4, 
// or the old element having value 14?

Say I have a C++ STL set of int, then I move the iterator to somewhere middle (the 5th element in the example), then I insert some more elements which the container may change the position of the elements. After that, where does the iterator points to?

If it is pointing to the old value instead of the position I specified, is there any method (not necessary using iterator) to keep getting the 5 th element even after the element has changed (without calling advance() again)? Thanks.


To clarify, I have tested by the following code:

st.insert(4);
it = st.begin();
st.insert(3);
st.insert(2);
cout << *it << endl;

It was printing 4, while in my situation I want to always access a element at specific position, say st.begin()+3 (if exist), thus the question

Upvotes: 1

Views: 1776

Answers (3)

John Perry
John Perry

Reputation: 2678

Going on the question in bold,

is there any method (not necessary using iterator) to keep getting the 5 th element even after the element has changed (without calling advance() again)?

No, there is no way to always access a specific position. At least one compiler implements sets as trees. Trees are often rebalanced in order to maintain efficiency of search, insert, etc. The penalty is that you can't count on any element to remain in any particular position after an insert.

Upvotes: 3

Ari0nhh
Ari0nhh

Reputation: 5920

std::set is an associative container, so position of its elements have no meaning. Your iterator is pointing to the same element, because std::set::insert is not invalidating iterators. There is no guarantee, that this will be 5th element although. If you need an container with the fixed positions, use std::vector or std::list instead.

Upvotes: 2

rodolk
rodolk

Reputation: 5907

It points to the same element. Not necessarily the same position in the set as the set is ordered. Read here: http://www.cplusplus.com/reference/set/set/insert/

Upvotes: 1

Related Questions