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<std::vector<int> > sparseArray(3,std::vector<int>(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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>
#include <cassert>

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<T> vec ;
};

int main()
{
    vec_2d<int> 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.