C ++ std :: vector :: data为什么返回的指针索引和向量索引不匹配?

长龙

我在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
法案

这张图片可能有助于说明

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] [   ]
        ^

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++ std :: vector:在向量位置求和

参加std :: vector C ++

为什么C ++会用零初始化std :: vector而不初始化std :: array?

C ++中的std :: vector与[]比较慢-为什么?

在 std::vector 中索引名称

当打印std :: vector <std :: pair>时,C ++“操作符<<”不匹配

C++ std::vector 的两个替代指针

C++:函数模板指针的 std::vector

在FreePascal中相当于C ++ std :: vector,std :: deque和std :: map

C ++ std :: vector <>与new []性能

访问多维C ++ std :: vector

独立的std :: threads的C ++ std :: vector

C ++性能std :: array vs std :: vector

C ++中的std :: vector与std :: array

如果向量为空,std :: vector :: data()应该返回什么?

在C ++中返回std :: vector的有效方法

什么是C ++ 17中的std :: vector推导指南?

用户定义的类型和C ++中的std :: vector

在一个结构内的c ++:std :: vector的std :: vector

为什么返回std :: vector仍在复制?

c ++ std regexp为什么不匹配?

不匹配调用 '(std::vector<std::vector<int> >) (int, std::vector<int>)'

C ++:错误无法从std :: vector <int> *转换为std :: vector <std :: vector <int>>

C ++从std :: vector <std :: function <... >>删除std :: function

基于向量大小在for循环中擦除std :: vector的索引

为什么不能在C ++中为std :: vector的字符串文字初始值设定项列表创建std :: vector <std :: string>?

C ++不将`std :: vector <std :: string>`“ overload”作为`main()`的参数的原因是什么?

使用std :: vector的互补向量

从std :: vector删除原始指针