Assigning a 2D vector in C ++

#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);
    }
 }

      

I am trying to assign a 2D vector. I am getting the following error:

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

      

+3


source to share


7 replies


Problem: Your vector is v

still empty and you cannot access v[i]

without clicking some vector in v.



Solution: Replace operator v[i].push_back(temp);

withv.push_back(temp);

+6


source


v[0]

empty, you should use v.push_back(temp);

You can use an approach at

to avoid this error:

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

      



Then you can access it via:

v.at(COLUMN).at(ROWS) = value;

      

+5


source


v[i].push_back(temp);

      

it should be

v.push_back(temp);

      

v

- type std::vector<vector<int>>

, v[i]

- typestd::vector<int>

+4


source


You can follow this process:

#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;
    }
 }

      

+4


source


You should use v

instead 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;
}

      

+4


source


Think of it this way: "How do I insert a temp variable of type T

into my vector std::vector<T>

?" In your case, this is:

v.push_back(temp);

      

T

the vector itself is irrelevant. Then, to print your vector (s), you can use two loops 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;
}

      

+3


source


Just do it ...

#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];
}

      

}

0


source







All Articles