Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing elements with std::vector::data()

For this piece of code I am using the data() method of the vector to access its elements:

#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;
}

Which generates

myvector contains: 10 20 0 100 0

The question is why p[2] is 0? Assuming myvector.data() is a pointer to the first element (index 0), then p[0] is 10 which fine. ++p points to the next element which is p[1] and that is 20 which is also fine. Now, p[2] is the next element after p[1]. So, the sequence should be 10 20 100. Whats is the mistake here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You incremented p by 1 and then wrote into p[2], which effectively now is myvector[3].

Writing to p[1] would write to the field adjacent to *p.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading