【问题标题】:C++ Vectors: Why is this piece of code not working?C++ 向量:为什么这段代码不起作用?
【发布时间】:2011-07-24 16:44:41
【问题描述】:
vector< vector< vector<int> > > myArray(5, vector< vector<int> >(4));
vector<int> testArray();
myArray[0][0].push_back(testArray);

我不明白。我只是想在其中添加一个新元素。

编辑:第二行错误,但这仍然无法编译。

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector< vector< vector<int> > > myArray(5, vector< vector<int> >(4));
    vector<int> testArray;
    myArray[0][0].push_back(testArray);
    return 0;
}

编译错误:

pnt.cpp:在函数“int main()”中: pnt.cpp:8: 错误: 没有匹配函数调用‘std::vector >::push_back(std::vector >&)’ /usr/include/c++/4.4/bits/stl_vector.h:733:注意:候选者是:void std::vector<_tp _alloc>::push_back(const _Tp&) [with _Tp = int, _Alloc = std::分配器]

【问题讨论】:

  • 我不知道有什么更好的方法。我正在移植一些 Python 代码,因为它效率低下。这是我能想到的最快的方法,看起来还是有点干净。
  • 您看到了什么错误?是编译错误还是运行时问题?

标签: c++ arrays vector


【解决方案1】:
vector<int> testArray();

应该是:

vector<int> testArray;

vector&lt;int&gt; testArray(); 是一个名为testArray 的函数的前向声明,它返回vector&lt;int&gt;

你也有太多的间接级别:

myArray[0].push_back(testArray);

myArray[0][0] = testArray;

【讨论】:

  • @cBMtb 然后您需要使用确切的错误消息更新您的问题。 Erik 的回答修复了代码中的 一个 错误。很难看出是否还有更多。
  • 等等,我有一个矩阵,每个元素都有一个向量。当我想将元素放在 [0][0] 向量中时,为什么要使用 myArray[0] 而不是 myArray[0][0]?
  • @cBMtb,在[0][0] 级别,您要插入ints,而不是另一个向量。
【解决方案2】:

myArray 是一个向量的向量 int 的向量。 myArray[0] 是 int 向量的向量。这是您需要 push_back 的 int 向量的地方,如下所示:

std::vector< std::vector< std::vector<int> > > myArray(5, std::vector< std::vector<int> >(4));
std::vector<int> testArray;
myArray[0].push_back(testArray);
return 0;

使用 myArray[0][0] 您访问的是 int 向量,而不是 int 向量的向量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 2010-09-18
    相关资源
    最近更新 更多