我在http://www.cplusplus.com/reference/vector/vector/data/中找到了一个std :: vector的例子。
// 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;
}
,结果是
myvector contains: 10 20 0 100 0
我的问题可能很愚蠢,但我真的不明白这里发生了什么。我们直接指向了向量的内存。然后我们为第一个元素(索引0)赋值10,移动到第二个元素并为其赋值20(索引1)。最后,我们为第三个元素(索引2)赋值100。答案应该如下吗?
10 20 100 0 0
答案 0 :(得分:22)
这张图片可能有助于解释
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] [ ]
^
答案 1 :(得分:1)
示例的输出是正确的。让我在下面演示 -
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
答案 2 :(得分:0)
std::vector<int> myvector (5); ==> [0,0,0,0,0]
int* p = myvector.data(); // p points to element 0
*p = 10; // element 0 is now 10
++p; // shift position of p to the next element
*p = 20; // element 1 is now 20
p[2] = 100; // Using p as reference, go 2 positions to right and assign the value of 100 to the element found at that position.
输出正确[10,20,0,100,0]