ideone

useful pieces of codes

View on GitHub

Question

When we find() an element in a set, the iterator for the set which is returned, points to the object itself or the position of the object in the set?

That is when a new object is added in the set, will the iterator be pointing to the same object, or is it going to change due to rearrangement of the elements of the set?

Short Answer

It points to the object, and not the position.

Long Answer

Question becomes irrelavent because, from the iterator we cannot know the position of the object in the set, i.e., syntax it-2 or it-h.begin() doesn’t work. Iterator doesn’t store any position information, it only points to the object of the set directly.

But it is an iterator at the end so it has some kind of position information because it can go to the next and previous elements of the set in constant time. There comes the part that it is a bi-directional iterator and not the random-access iterator.

Execution

https://ideone.com/odvz6E

Code

#include <iostream>
#include <set>
using namespace std;

int main() {
	set<int> h;
	set<int>::iterator i;
	h.insert(2);
	i = h.find(2);
	cout<<"two: "<<*i<<endl;
	// cout<<"position: "<<i-h.begin()<<endl;	// compilation error
	h.insert(3);
	i++;
	i--;
	cout<<"three-one: "<<*i<<endl;
	// cout<<"position: "<<i-h.begin()<<endl;	// compilation error
	h.insert(1);
	cout<<"one+one: "<<*i<<endl;
	// cout<<"position: "<<i-h.begin()<<endl;	// compilation error
	return 0;
}

Ideone it!