6
#include<bits/stdc++.h>
using namespace std;
main()
{
    vector<vector<int> > v;
    for(int i = 0;i < 3;i++)
    {
        vector<int> temp;
        for(int j = 0;j < 3;j++)
        {
            temp.push_back(j);
        }
        //cout<<typeid(temp).name()<<endl;
        v[i].push_back(temp);
    }
 }

我正在尝试分配给二维向量。我收到以下错误

No matching function for call to 
std ::vector<int>::push_back(std::vector<int> &)
4

7 回答 7

8

问题:你的向量是空的,如果不推入 v 中的任何向量,v你就无法访问。v[i]

解决方案:将语句替换v[i].push_back(temp);v.push_back(temp);

于 2017-07-21T04:38:05.570 回答
5

v[0]是空的,你应该使用v.push_back(temp);

您可以使用at方法来避免此错误:

for(int i = 0; i < 3; i++){
   vector <vector <int> > v;
   vector <int> temp;
   v.push_back(temp);
   v.at(COLUMN).push_back(i);
}

然后您可以通过以下方式访问它:

v.at(COLUMN).at(ROWS) = value;
于 2017-07-21T04:47:25.157 回答
5

你可以按照这个过程:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<vector<int> > v;
    for(int i = 0;i < 3;i++)
    {
        vector<int> temp;
        for(int j = 0;j < 3;j++)
        {
            temp.push_back(j);

        }
        //cout<<typeid(temp).name()<<endl;
        v.push_back(temp);
    }
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cout << v[i][j] << " ";
        }
        cout << endl;
    }
 }
于 2017-07-21T04:43:36.550 回答
4

您应该使用v而不是v[i]. (C++11)

#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char* argv[])
{
    vector<vector<int> > v;
    for(int i = 0;i < 3;i++)
    {
        vector<int> temp;
        for(int j = 0;j < 3;j++)
        {
            temp.push_back(j);
        }

        v.push_back(temp);
    }

    for (auto element: v) {
        for (auto atom: element) {
            cout << atom << " ";
        }
        cout << "\n";
    }

    return 0;
}
于 2017-07-21T04:45:33.623 回答
4
v[i].push_back(temp);

应该

v.push_back(temp);

v是 的 类型是std::vector<vector<int>>v[i]类型std::vector<int>

于 2017-07-21T04:39:06.347 回答
3

可以这样想:“如何将类型的变量tempT插入到我的向量中std::vector<T>?” 在您的情况下,它是:

v.push_back(temp);

T本身是一个向量并没有什么区别。然后打印出你的向量(向量),你可以使用两个for循环:

for (std::size_t i = 0; i < v.size(); i++){
    for (std::size_t j = 0; j < v[i].size(); j++){
        std::cout << v[i][j] << ' ';
    }
    std::cout << std::endl;
}
于 2017-07-21T04:52:18.693 回答
0

去做就对了...

#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<vector<int> > v;
    for(int i = 0; i < 3; i++)
    {
        vector<int> temp;
        for(int j = 0; j < 3; j++)
        {
            temp.push_back(j);
        }
        v.push_back(temp);//use v instead of v[i];
    }
}
于 2017-08-01T12:15:01.010 回答