2D Vector - push_back, erase

std::vector< std::vector<double> > my_vector;

I have this 2D vector. How can I insert a double element to position(0,0) i.e how can I push_back such that my_vector[0][0] contains a double value. Subsequently, how could I add a double element to position my_vector[1][0]. Any other solution other than this:-

1
2
3
4
5
6
7
std::vector<double> tmp_vector;
my_vector.push_back(tmp_vector);
/* for my_vector[0][0] */
my_vector[0].push_back(2.5);
/* for my_vector[1][0] */
my_vector.push_back(tmp_vector);
my_vector[1].push_back(3.5);



How can I delete an element from a 2D vector? for example I want to remove element my_vector[2][3]. Could I use the erase function? Please help how to use erase function.

ps: I know it would be a very inefficient way of executing a program but I dont really care about time-optimization. Important for me is to finish the job somehow!

You would call .erase() on the second vector, on the third element.

e.g. to delete [4][4]:

 
my_vector[4].erase(my_vector.begin()+3);
firedraco

If I want to delete a row say 3rd row, would this work??
 
my_vector.erase(my_vector.begin()+2);


or can I not use just this? I dont think I would ever need to use begin() as it always will be zero..

 
my_vector.erase(2);


Or am I missing some point?
Also another question, how can I pass a vector to a function, such that changes in the vector can be seen in the main function (pass by reference, pass by pointers)?

Ex:-
1
2
3
4
5
6
7
8
9
10
11
void My_Func(int **my_array)
{
my_array[0][0] = 5;
}
int main()
{
int a[5][10];
cout<<a[0][0];
My_Func(a);
cout<<a[0][0];
}


output:-
0
5

Now I would like a function:-
1
2
3
4
5
6
7
8
9
10
11
void My_Func(vector< vector<int> > my_vector)
{
 my_vector[0][0] = 5;
}
int main()
{
vector< vector<int> > a(5,10);
cout<<a[0][0];
My_Func(a);
cout<<a[0][0];
}


output:-
0 (not sure!)
5

ps: I wouldnt implement the my_func in this manner(as it could access illegal addresses if I for example use a[100][100]), but its just to make the question more clear.
vector.begin() does not return 0. It returns an iterator to the first element in the vector whose index is zero.
So yes, you need begin() + 2.

1
2
3
void My_Func( vector<vector<int> >& my_vector )
{
}

Topic archived. No new replies allowed.