【问题标题】:How can i correctly create a vector of arrays?如何正确创建数组向量?
【发布时间】:2021-03-26 02:15:06
【问题描述】:

我是 C++ 新手,我正在尝试创建一个 std::vector 数组,但是每当我 push_back 一个新元素时,似乎所有以前的元素都会被我刚刚添加的新值覆盖。 (我需要使用 c++ 默认数组而不是 std::array 或其他容器,因为我需要将它们传递给只接受这些的函数)。

以下代码和输出显示了正在发生的事情的示例:

std::vector<int*> tuples;
for( int i = 0; i < 10; i++ )
{
    for( int j = 0; j < 5; j++ )      
    {
        int tuple[] = { i, j };
        tuples.push_back( tuple );      
    }
}

for( int i = 0; i < tuples.size(); i++ )        
    std::cout << i << "   " << tuples[i][0] << " " << tuples[i][1] << std::endl;

At the end every array in the vector has elements {9, 4}, which are the last values reached by i and j respectively

【问题讨论】:

  • 数组不是指针
  • 指针不是数组。尝试将std::vector&lt;std::array&lt;int ,2&gt; &gt; 用于tuplesstd::array&lt;int, 2&gt; 用于tuple。您可能还想查找std::pair 作为std::array&lt;int, 2&gt; 的替代品。

标签: c++ arrays pointers vector


【解决方案1】:

在循环的每次迭代中,您不会推回数组,而是将 指针 推回具有自动存储持续时间的数组,然后超出范围。 (从概念上讲,每次迭代都会创建一个新数组,但实际上编译器会对其进行优化。)

所以你最终会得到一个std::vector 的悬空指针,而尝试取消引用这些指针的行为是未定义

一种解决方案是使用std::array 作为std::vector 有效负载。请注意,std::array 有一个 data() 函数,它产生底层数组 - 这将提供与需要 int* 参数的函数的兼容性。

【讨论】:

  • 补充:使用std::array,然后调用data() 获取底层C-array(如果需要)
  • @dave:好点:不妨让答案对 OP 有用。
  • 或者,如果首选旧式指针,您可以使用int* tuple = new int[2]{ i, j }; 代替int tuple[] = { i, j };(但不要忘记在某个时候delete[] 每个元素)。跨度>
猜你喜欢
  • 1970-01-01
  • 2021-04-26
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-22
相关资源
最近更新 更多