Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems using 3-dimensional vector

Tags:

c++

vector

How can I work with a 3 dimensional vector in C++?

vector<vector<vector<int> > > vec (1,vector<vector<int> >(1,vector <int>(1,12)));

When I try something like this

cout << vec[0][0][0]; vec[0][0][1] = 13;

everything works just fine.

The problem is that I can only change the last elements. If I try accessing the first and second element, like this

vec[0][1][0] = 13;

or this

vec.push_back(vector<vector<int > >());
vec[0].push_back(vector<int>()); 
v[1][0].push_back(13);

my program crashes.

How can I add and access elements in a 3d vector?

like image 972
NonSense Avatar asked Feb 10 '23 14:02

NonSense


1 Answers

I would never do vector<vector<vector<int> > > as in this way you have many allocations what could be expensive. I would simply use vector<int> with smart indexing (e.g.: see below). If you will work with double based matrices, in this way intel MKL or any other BLAS library easily could be used.

Its price is increased complexity when matrix sizes are changed, but you could win many in performance.

Useful link: C++ FAQ.

static int const M = 16;
static int const N = 16;
static int const P = 16;

inline int& set_elem(vector<int>& m_, size_t i_, size_t j_, size_t k_)
{
    // you could check indexes here e.g.: assert in debug mode
    return m_[i_*N*P + j_*P + k_];
}
inline const int& get_elem(const vector<int>& m_, size_t i_, size_t j_, size_t k_)
{
    // you could check indexes here e.g.: assert in debug mode
    return m_[i_*N*P + j_*P + k_];
}

vector<int> matrix(M*N*P, 0);
set_elem(matrix, 0, 0, 1) = 5;
like image 138
Naszta Avatar answered Feb 13 '23 03:02

Naszta