Sign in to follow this  
raptorstrike

pretty simple question

Recommended Posts

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]

Share this post


Link to post
Share on other sites
I think the easiest way would be:
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.

Share this post


Link to post
Share on other sites
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[i].push_back(4);
};
std::cout << bla[0][0];
system("pause");
};

it dosnt work. i get a run-time error

Share this post


Link to post
Share on other sites
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[i].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[i], but blah[i] 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[i].push_back(4);
};

std::cout << bla[0][0];
system("pause");
};

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this