### 2d vector

How would I create a vector matrix of size 3*4 using vector and with nested loop?

I dont want to use this
 `` `` `` std::vector > sparseArray(3,std::vector(4));``
 I dont want to use this

why not?
> How would I create a vector matrix of size 3*4 using vector and with nested loop?

Something along these lines, perhaps:

 ``123456789101112131415161718192021222324252627282930313233`` ``````#include #include #include template < typename T > struct vec_2d { vec_2d( std::size_t nrows, std::size_t ncols ) : nrows(nrows), ncols(ncols), vec(nrows*ncols) {} T* operator[] ( std::size_t row_num ) { assert( !vec.empty() && row_num < nrows ) ; return std::addressof( vec.front() ) + row_num*ncols ; } std::size_t nrows ; std::size_t ncols ; std::vector vec ; }; int main() { vec_2d vec(5,7) ; for( std::size_t i = 0 ; i < vec.nrows ; ++i ) for( std::size_t j = 0 ; j < vec.ncols ; ++j ) vec[i][j] = i*10 + j + 11 ; for( std::size_t i = 0 ; i < vec.nrows ; ++i ) { for( std::size_t j = 0 ; j < vec.ncols ; ++j ) std::cout << vec[i][j] << ' ' ; std::cout << '\n' ; } }``````

http://coliru.stacked-crooked.com/a/26a2aea9e588d870

Note that there would be a significant performance improvement (due to better locality of reference) only when the number of rows is somewhat large and the number of elements in each row is not very huge.
Last edited on
Topic archived. No new replies allowed.