Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::vector::data Why do the returned pointer index and the vector index not match? [closed]

Tags:

c++

c++11

vector

I found an example of std::vector in http://www.cplusplus.com/reference/vector/vector/data/.

// vector::data
#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;
}

and the result is

myvector contains: 10 20 0 100 0

My question may be silly but I don't really understand what happened here. We got a direct pointer to the memory of the vector. Then we assign the value 10 for the first element (index 0), move to the second element and assign the value 20 to it (index 1). Finally, we assign the value 100 for the third element (index 2). Should the answer be as follow?

10 20 100 0 0
like image 808
Thế Long Avatar asked Oct 23 '17 02:10

Thế Long


People also ask

What does Vector Data Return C++?

vector data() function in C++ STL The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements.

How do I pass a vector to a specific index?

The most idiomatic way is to make your function take iterators: template<typename It> It::value_type maxsubarray(It begin, It end) { ... } and then use it like this: std::vector<int> nums(...); auto max = maxsubarray(begin(nums) + 2, end(nums));

Can we use index in vector C++?

Indexing works on Vectors, So just Acces it by using index.


2 Answers

This picture might help explain

int* p = myvector.data();
[   ] [   ] [   ] [   ] [   ]
  ^

*p = 10;
[10 ] [   ] [   ] [   ] [   ]
  ^

++p;
[10 ] [   ] [   ] [   ] [   ]
        ^

*p = 20;
[10 ] [20 ] [   ] [   ] [   ]
        ^

p[2] = 100; // [2] is relative to where p is
[10 ] [20 ] [   ] [100] [   ]
        ^
like image 118
Bill Avatar answered Oct 27 '22 01:10

Bill


The output of the example is right. Let me demonstrate it below -

std::vector<int> myvector (5); // creating vector with size 5, elements are 0,0,0,0,0

  int* p = myvector.data(); //taking reference of the vector, p now points the first element of vector

  *p = 10; // it means first element is now 10
  ++p; // p now points second element of the vector
  *p = 20; // 2nd element is now 20
  p[2] = 100; //p[2] is the 4th element now because of two position shifting and it is now 100
  // vectors elements are now 10, 20, 0, 100, 0
like image 30
Naseef Chowdhury Avatar answered Oct 26 '22 23:10

Naseef Chowdhury