Paul Sen
Paul Sen

Reputation: 554

STL vector operator data

I was just reading about vectors when i came across the data operator.In below example data operator is being used.

#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (5);

  int* p = myvector.data();

  *p = 10;
  ++p;
  *p = 20;
  p[2] = 100;

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); ++i)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

Output:

myvector contains: 10 20 0 100 0

My question is why 0 at the place 0f 100 and 100 is moved one location backward. as:

  1. p is equivalent myvector[0] which is given value 10.
  2. ++p; now p points to myvector[1] given value 20
  3. so after 20, 100 should come so why there is 0.

Upvotes: 1

Views: 92

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117886

Because you already mutated p when you did

++p

So this operation

p[2]

is already offset by 1 index so it is as if you did

p[2 + 1]

from the original address of p

Upvotes: 7

Related Questions