how to detect whether two iterators point to the same element of a container

For some reason I need to store the iterators of a container and judge whether two iterators point to the same element. I found that whether two iterators point to the same element of a container can't be decided by "itr1 == itr2". The following code is a short demonstrate of that. Then, how can I make the decision properly? Thanks for any hints.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>

using namespace std;

int main()
{
	vector<int> v;
	for(int i = 0 ; i < 10 ; i++) v.push_back(i);
	vector<int>::iterator it1 = v.end() - 1;

	vector<int>::iterator it2 = v.end() - 1;
	if(it1 == it2) {cout<<"it1 == it2"<<endl;}
	else {cout<<"it1 != it2"<<endl;}

	v.erase(v.begin());

	vector<int>::iterator it3 = v.end() - 1;
	if(it1 == it3) {cout<<"it1 == it3"<<endl;} 
	else {cout<<"it1 != it3"<<endl;}

	cout<<"*it1 == "<<*it1<<endl;
	cout<<"*it2 == "<<*it2<<endl;
	cout<<"*it3 == "<<*it3<<endl;
}
Last edited on
if( &(*iter1) == &(*iter2) )
thanks for the prompt reply
No no no no no.

You can compare iterators to see if they point to the same element with
if( it1 == it2 )

Your program doesn't work because it has a bug.

Calling erase() on a vector invalidates all iterators held prior to the erase.

erase() is invalidating it1.
Topic archived. No new replies allowed.