I did some research and found out that
Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays.
So if vector
is guaranteed to use contiguous storage it would be safe to use code like this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> V = { 4, 2, 8, 4, 4, 6 };
for (auto &i : V)
{
cout << i << "(pos " << (&i - &V.front()) << ")" << endl;
}
return 0;
}
Am I right or am I making wrong assumptions? The code works. The question is if it's guaranteed to work. foreach
is very practical and its only problem is getting a element's relative position.
So, can pointers to a vector element be used safely to determine its position in the container?