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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With