2D and 3D vectors

Creating a 3D vector

I recently came across the need for a dynamic array for a game solver I have been working on. There was a lot of confusion on the creation and use of the three dimensional vectors. The following write-up is to help people utilize 3D vectors. A vector is basically a dynamic array that can add and remove elements while resizing itself. Like an array the vectors are told what type they are. For these examples we will be using the int type.

.:The Creation:.

Let’s start off with a standard vector which may look something like the following.

//this is a vector holding int types
std::vector <int> myVector;

//this is the same thing but initialized to have 9 elements all which equal 0.
std::vector <int> sizedVector(9,0);

What we are doing is creating a dynamic array of integers named myVector. Since it is dynamic in the first declaration used allows declaration with no size or values. The second declaration creates a vector that contains 9 elements all equal to 0. Now that you have a little back ground we can make a 2D vector.

//a 2d vector of int
std::vector < std::vector <int> > vec2d;

//a 2D vector that has been initialized
std::vector <std::vector <int> > vec2dInit(9,std::vector<int>(9,0));

Slightly more complicate; let’s break down what is happening here. The first declaration is creating a vector of type vector instead of int. Exactly like 2d arrays or strings which are an array of arrays of a certain type except you don’t have to manage memory, and allows for dynamic sizes. Now for the fun stuff, 3D vector creation.


//declare the 3D vector of type int named vec3D
std::vector<std::vector<std::vector<int> > > vec3D;

//declare the same 3D vector but initialized.
std::vector<std::vector<std::vector<int> > > vec3D(9, std::vector<std::vector<int> > (9, std::vector<int>(9,0)));

Confused? You should be able to see a pattern of incrementation here though. Every time we add a dimension we duplicate the same steps we did before which is to add another vector of int type. Now that the 3D vector exists, how can it be used?

.:Read and write to the 2D 3D vectors:.
Assigning data and reading from the vectors is also very similar to a 2D or 3D array.

//write some data into the 2dVector
vec2d[3][2]= 3;

//write some data to 3dVector
vec3d[3][2][3]=4;

//read from 2dVector
int x = vec2d[3][2];

//read from the 3dVector
int x = vec3d[3][2][3];

In addition you can also use the container features of each element of the vectors as shown below.


//write to the end of the container
vec2d[2][3].push_back(4);

//write to the end of the 3D container
vec3D[1][2][3].push_back(4);

//find the number of elements in the last vector
int x = vec3D[1][2].size();

//the same can be done for the underlying vectors as well. 
int x = vec3D[1].size();

For my project i found it was easier to use a struct to hold the information i required. Hopefully this helped someone.