# 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 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 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 on other sites
Here's a similar question I asked recently, with some relevant information.

Jim.

##### Share on other sites
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

##### Share on other sites
Quote:
 Original post by raptorstrikeyeah the size isnt the issue i thought that the [index] push back would work too but take a look at this#include #include using namespace std;int main(){ vector< vector > 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.

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

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627719
• Total Posts
2978790

• 9
• 21
• 14
• 12
• 42