pretty simple question
i just want to know how to push_back() an element into a 2d vector like so:
vector< vector<int> > bla;
this is the way i thought would do it
bla[0].push_back(9);
for example but it dosnt work. i dont get any errors but no results either. i even did a little test program in dos to see if it was just my function and still nothing to can some one help me out here?
thanks a lot [grin]
I think the easiest way would be:
Although this is only when you know that the first dimension also needs to be resized. If the first dimension is already the size you want, you just want to add an element to one of the first-dimension elements, then bla[index].push_back(9) should work fine.
bla.resize(bla.size() + 1);bla.back().push_back(9)
Although this is only when you know that the first dimension also needs to be resized. If the first dimension is already the size you want, you just want to add an element to one of the first-dimension elements, then bla[index].push_back(9) should work fine.
yeah the size isnt the issue i thought that the [index] push back would work too but take a look at this
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< vector<int> > bla;
for(int i = 0; i < 10; i++)
{
bla.push_back(4);
};
std::cout << bla[0][0];
system("pause");
};
it dosnt work. i get a run-time error
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< vector<int> > bla;
for(int i = 0; i < 10; i++)
{
bla.push_back(4);
};
std::cout << bla[0][0];
system("pause");
};
it dosnt work. i get a run-time error
ok its NOT a big deal ill just use an array. and ill have to look into a better alternative for when i relly do need it
Quote:Original post by raptorstrike
yeah the size isnt the issue i thought that the [index] push back would work too but take a look at this
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< vector<int> > bla;
for(int i = 0; i < 10; i++)
{
bla.push_back(4);
};
std::cout << bla[0][0];
system("pause");
};
it dosnt work. i get a run-time error
you are trying to access invalid memory, and the program is crashing. you try directly accessing the vector using blah, but blah doesn't exist. remember, the vector starts out as empty, so you can't try to access any index untill somethings in the vector.
try this instead:
int main(){ vector< vector<int> > bla; //put 10 vectors inside of the outer vector bla.resize(10); //for each of these vectors inside the vector //we could do i < bla.size()... for(int i = 0; i < 10; i++) { bla.push_back(4); }; std::cout << bla[0][0]; system("pause");};
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement