I am trying to create a 3D vector and then populate it with values. Firstly I want to create a 3D vector of size 100 with all initial values set to zero. I know that to do this in the 1D case the code would read as follows:

``vector<float> vec (100, 0)``

I want to do the same thing with a 3D vector. How would the code look? I'm guessing something like

``vector<vector<vector<float> > > vec (100,0);``

Next, I want to assign certain entries of the vector. In the 1D case I would write something like:

``vec.at(3) = 5.336``

How do I index a 3D vector like this?

I want to do the same thing with a 3D vector. How would the code look?

You can do it like this:

``vector<vector<vector<float> > > vec (5, vector<vector<float> > (5, vector<float> (5, 0) ) );``

The above creates a 5 x 5 x 5 3D vector, with all initial values set to zero.

How do I index a 3D vector like this?

You can do it like this:

``````vec.at(1).at(2).at(3) = 5.5;

//or, if you don't want bounds checking...

vec[1][2][3] = 5.5;``````

However, for performance reasons, it would be better to create
a wrapper around a 1D vector that mimics 3D behaviour, like this:

``````#include <iostream>
#include <vector>

template <class T>
class Vector3D
{
public:

Vector3D(unsigned size_i_, unsigned size_j_, unsigned size_k_):
size_i(size_i_), size_j(size_j_), size_k(size_k_)
{ data.resize(size_i*size_j*size_k); }

Vector3D(unsigned size_i_, unsigned size_j_, unsigned size_k_, const T & default_value):
size_i(size_i_), size_j(size_j_), size_k(size_k_)
{ data.assign(size_i*size_j*size_k, default_value); }

T & operator () (unsigned i, unsigned j, unsigned k)
{ return data[i*size_j*size_k + j*size_k + k]; }

// or, if you want bounds checking...
// data.at(i*size_j*size_k + j*size_k + k);

const T & operator () (unsigned i, unsigned j, unsigned k) const
{ return data[i*size_j*size_k + j*size_k + k]; }

// or, if you want bounds checking...
// data.at(i*size_j*size_k + j*size_k + k);

//...

// more member functions
// (e.g. resize etc...)

//...

private:

unsigned size_i;
unsigned size_j;
unsigned size_k;

std::vector<T> data;
};

int main()
{
Vector3D<int> v3d(2,3,4,100);

v3d(1,2,3) = 0;

std::cout << v3d(0,1,2) << std::endl;
std::cout << v3d(1,2,3) << std::endl;

return 0;
}``````

Finally, you can always use boost::multi_array -> http://www.boost.org/doc/libs/1_47_0/libs/multi_array/doc/index.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.