how to declare 2D vector

Mar 9, 2010 at 10:51am
I want to define a 3x4 2D vector, how can I do it?

For 1D vector, I can do

std::vector<double> a(3);

but for 2D?
Mar 9, 2010 at 11:31am
it's impossible, because vector is a dynamic array, but not matrix(2D array).
Mar 9, 2010 at 12:24pm
Sure its possible:
std::vector<std::vector<double> > array;
Mar 9, 2010 at 12:53pm
it's impossible, because vector is a dynamic array, but not matrix(2D array).


If we can have a contructor for 1D array, there could also be a for a 2D array.

Sure its possible:
std::vector<std::vector<double> > array;


Thanks but i want to declare it for specific size(say 3*4), and not keep doing 'push_back's latter.
Mar 9, 2010 at 1:02pm
Well then its impossible, unless you use a 1D vector and have it simulate a 2D array
Mar 9, 2010 at 1:20pm
Nevermind, I wrote a small function and it does it for me!

1
2
3
4
5
6
7
8
9
10
11
12
13
   void Change2DVectorSize(vector< vector<double> > &a, int nRows,int nColumns)
   {
	   int i;
	   vector<double> CurrRow;

	   a.clear();

	   for(i=0;i<nColumns;i++)
		   CurrRow.push_back(0.0);

	   for(i=0;i<nRows;i++)
		   a.push_back(CurrRow);	    
   }


It would have been nice if such a function was inbuilt in C++. Btw, can somebody help me change the above code from 'double' to 'template'? So that I can reuse it for other datatypes.. int etc. Let me give it a try:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   template < typename T >
   void Change2DVectorSize(vector< vector<T> > &a, int nRows,int nColumns)
   {
	   int i;
	   vector<T> CurrRow;

	   a.clear();

	   for(i=0;i<nColumns;i++)
		   CurrRow.push_back((T)0);

	   for(i=0;i<nRows;i++)
		   a.push_back(CurrRow);	    
   }
Mar 9, 2010 at 1:22pm
 
std::vector< std::vector< double > > twoDMatrix( 3, std::vector< double >( 4 ) );


done.
Mar 9, 2010 at 1:26pm
Jsmith

Now thats what I call to the point and perfect answer!! Thanks.

Is my use of template correct? (Am quite new to it)
Mar 9, 2010 at 1:38pm
It is.
Topic archived. No new replies allowed.