Jump to content
  • Advertisement
Sign in to follow this  
raptorstrike

pretty simple question

This topic is 4979 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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.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.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");
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!