2

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.

Source: http://www.cplusplus.com/reference/vector/vector/

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?

LHLaurini
  • 1,737
  • 17
  • 31
  • 3
    See [this answer](http://stackoverflow.com/a/10962459/1783614) – yizzlez Aug 03 '15 at 00:37
  • @awesomeyi Thanks. I guess it's safe as long as I am careful. – LHLaurini Aug 03 '15 at 00:44
  • @LHLaurini Your code may fail miserably if you hold onto those pointers and the vector is resized. You should not be pointing to positions in the vector if your real goal is to refer to those pointers later on. I am assuming your program is much bigger than this toy example. – PaulMcKenzie Aug 03 '15 at 00:45
  • @PaulMcKenzie Yes, I know that. I have actually some experience with that problem. Solved it storing indices instead of pointers (guess I could use iterators too, gonna check that out). That's actually not what the question is about, but thank you anyways. – LHLaurini Aug 03 '15 at 00:49
  • @LHLaurini To safely determine the position, use `std::distance`. Over-pointerizing code often causes disabling of optimizations that the compiler can perform. – PaulMcKenzie Aug 03 '15 at 00:51
  • @PaulMcKenzie `std::distance` uses iterators, which is actually useless in this context (foreach loop). – LHLaurini Aug 03 '15 at 16:47
  • @LHLaurini `std::distance` works with pointers. A pointer *is* an iterator. – PaulMcKenzie Aug 03 '15 at 17:06

1 Answers1

1

Could be safe,but not good. The result really relay on the the implement detail of Allocator/Iterator.You can define your own allocator that not follow contiguous storage in theory. Please use Iterator to calculate the relative position.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Dean Song
  • 341
  • 1
  • 10