Why does vector's random access iterator gives the same memory address unlike pointers?

Viewed 56
vector<int>::iterator it;
for(it=v.begin();it<v.end();it++)
{
     cout <<&(it)<<" ";
     cout<<(*it)<<" ";
}

It outputs:

0x7fff6667cdf0 7 0x7fff6667cdf0 14 0x7fff6667cdf0 15 0x7fff6667cdf0 16

Note the address is same each time, the question is why?

1 Answers

You're getting the address of the same object it, then you'll get the same address every time. The element pointed by the iterator changes, but the address of the iterator itself (it is an object and has its own address) won't change.

It's same for pointer variable too, if you're getting the address of the pointer itself. E.g.

int* p;
size_t s;
for (p = v.data(), s = 0; s < v.size(); s++, p++)
{
    cout <<&(p)<<" ";
    cout<<(*p)<<" ";
}
Related