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
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 to share
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 to share
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 to share