# Thread: STL vector question

1. ## STL vector question

i want to create a 2D matrix using vector. why the below is wrong?

typedef std:vector<int> x
typedef std:vector<x> y

y matrix(7, x somevar(7) ) // trying to create 7 x 7 matrix

look the second index ... x some_var(7) , i have written explicitly to crete a vector of 7 elements using typedef and then repalcing that into the matrix as the second argument.

is it valid ?

if not why it is not valid and what i should i do ?

thanks

2. The whole point of having a vector is so that you can create an array without worrying about the size, it just grows as you push new things into it.
Besides, I don't think the constructor takes those arguments. Have you tried it? You should try doing a dummy program just to test some scenario and if you have problems, post.
And remeber, use code tags when posting code.

3. Code:
```y matrix(7,x(7));
//or
x somevar(7);
y matrix(7, somevar);```
However, the vector of vectors solution is really only usefull if some rows may be longer than others. In most cases I prefer to roll my own matrix class that overloads () to wrap my index calculations.
Code:
```template<class Scalar=int>
class matrix {
size_t col;
std::vector<Scalar> v;
public:
matrix(size_t rrow=0,size_t ccol=0) : col(ccol), v(row*col) {}
Scalar & operator(size_t x, size_t y) {
return v[y*col+x];
}
};```
adding push_row, push_col taking refs to vectors and so forth as needed. This also adds a nice place to switch from row-major to col-major. The main thing is that once you get down to the assembly level all 2d arrays are really just long blocks of contiguous memory addressed with some multiplication as well. The matrix[x][y] syntax, where matrix is a vector of vectors, is deceptively simple, you are actually asking for a good bit more work than a multiply and add.

Popular pages Recent additions