在c ++中分配二维向量

pro*_*ver 4 c++ 2d-vector

#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);
    }
 }
Run Code Online (Sandbox Code Playgroud)

我正在尝试分配一个二维向量.我收到以下错误

No matching function for call to 
std ::vector<int>::push_back(std::vector<int> &)
Run Code Online (Sandbox Code Playgroud)

Itb*_*eed 7

问题:你的矢量v是空的,如果不v[i]按v中的任何矢量你就无法访问.

解决方法:更换声明v[i].push_back(temp);v.push_back(temp);


Md.*_*que 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;
    }
 }
Run Code Online (Sandbox Code Playgroud)


Shi*_*ing 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);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以访问它:

v.at(COLUMN).at(ROWS) = value;
Run Code Online (Sandbox Code Playgroud)