【问题标题】:C++ std::vector::data Why do the returned pointer index and the vector index not match? [closed]C++ std::vector::data 为什么返回的指针索引和向量索引不匹配? [关闭]
【发布时间】:2018-04-03 12:29:08
【问题描述】:

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

【问题讨论】:

  • p[2] 没有访问第三个元素(它正在访问第四个元素,如您的结果所示)。请记住,您已经增加了p
  • @max66:我认为这个问题与由“简单的印刷错误”引起的问题属于同一领域。因此,我个人更喜欢在评论中添加一个非常简单的解释(所以 OP 仍然会得到帮助;我并非完全无情),同时也投票结束。
  • p[2] 视为p + 2 可能有助于您理解。这可能只是不使用 cplusplus.com 的一个很好的理由,因为他们的示例中令人困惑的部分与 data 无关
  • 标题不太可能帮助任何人找到问题,即使他们有同样的问题。如果您希望问题保持开放,我建议让问题更容易理解:提到指针、索引、指针算术……可能更具描述性。
  • @MatthieuM。标题可能不是特别具有描述性,但我认为改进的标题不会对这个问题有太大帮助,因为这个问题似乎归结为对指针运算的普遍缺乏理解,忘记了 ++p 或混淆了 @987654331 @ 与 myvector[2].

标签: c++ c++11 vector


【解决方案1】:

这张图片可能有助于解释

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

【讨论】:

    【解决方案2】:

    示例的输出是正确的。让我在下面演示一下 -

    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
    

    【讨论】:

      【解决方案3】:
      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]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-12
        • 2012-09-10
        • 2013-03-20
        • 1970-01-01
        • 1970-01-01
        • 2015-12-15
        • 2013-02-17
        相关资源
        最近更新 更多