#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 to a two dimensional vector. I am getting the following error
No matching function for call to
std ::vector<int>::push_back(std::vector<int> &)
One way to represent a two-dimensional vector is with vector components, which simply tell you how far the vector goes in each direction. For example, a vector with an x-component of 4 and a y-component of 3 that started at the origin would end at coordinates (4,3).
To initialize a two-dimensional vector to be of a certain size, you can first initialize a one-dimensional vector and then use this to initialize the two-dimensional one: vector<int> v(5); vector<vector<int> > v2(8,v); or you can do it in one line: vector<vector<int> > v2(8, vector<int>(5));
A vector can be initialized with all zeros in three principal ways: A) use the initializer_list, B) use the assign() vector member function to an empty vector (or push_back()), or C) use int or float as the template parameter specialization for a vector of initially only default values.
Problem: Your vector v
is empty yet and you can't access v[i]
without pushing any vector in v.
Solution: Replace the statement v[i].push_back(temp);
with v.push_back(temp);
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With