Normal Initialisation of 3D Vector
Normal Initialization of 3D Vector in C++
To initialize a 3D vector in C++, you can follow these steps:
Include the necessary header file: Before using the vector class, you need to include the
<vector>
header file in your source code. This file provides the necessary definitions and functions for working with vectors.Declare the vector: Declare a variable of type
vector<vector<vector<T>>>
, whereT
is the type of the elements you want to store in the vector. This declaration creates an empty vector.Set the size of the vector: Use the
resize()
function to set the size of the vector. Theresize()
function takes the desired size as its argument and resizes the vector accordingly. For example, to create a 3D vector with dimensionsx
,y
, andz
, you would use the following code:
cpp
vector<vector<vector<T>>> myVector;
myVector.resize(x, vector<vector<T>>(y, vector<T>(z)));
This code resizes the vector to have x
elements in the first dimension, each containing a vector with y
elements in the second dimension, each containing a vector with z
elements in the third dimension. The T()
part initializes each element with a default-initialized value of type T
.
- Access and modify the elements: You can access and modify the elements of the 3D vector using the usual indexing syntax. For example, to access the element at position
(i, j, k)
, you would usemyVector[i][j][k]
.
Here is an example that demonstrates the normal initialization of a 3D vector in C++:
#include <vector>
int main() {
int x = 3;
int y = 4;
int z = 5;
// Declare and resize the 3D vector
std::vector<std::vector<std::vector<int>>> myVector;
myVector.resize(x, std::vector<std::vector<int>>(y, std::vector<int>(z)));
// Access and modify the elements
myVector[1][2][3] = 42;
return 0;
}
This example creates a 3D vector with dimensions 3, 4, and 5, and assigns the value 42 to the element at position (1, 2, 3)
.