![]() |
VOOZH | about |
Initializing 3D vector refers to the process of assigning the initial values to the elements of 3D Vector. In this article, we will learn different methods to initialize the 3D vector in C++.
The simplest ways to initialize the 3D vector is by passing the elements inside the initializer list. This method is convenient for quick initialization when the number of items is less.
1 2 3 4 5 6 7 8 9 10 11 12
Explanation: The elements specified in the initializer list are used as initial value of 3D vector.
Apart from the above method, C++ also provides other different methods to initialize a 3D vector depending on the situation. Some of them are:
The 3D vector can also be initialized with the default value at the time of declaration.
vector<vector<vector<int>>> v(x, vector<vector<int>>(y, vector<int>(z, k)));
where x, y and z is the number of rows, number of column and depth of 3D vector respectively, and k is the default value by which we initialize the 3D vector.
11 11 11 11 11 11 11 11 11 11 11 11
Note: In this method, if we do not initialize the 3D vector with some default value, then by default it will be initialized by value of the int type which is 0.
The fill() function can also be used to initialize the 3D vector with any default value.
fill(v.begin(), v.end(), vector<vector<int>>(y, vector<int>(z, k)));
Here y and z is the number of columns and depth of 3D vector v, and k is the default value by which we initialize 3D vector.
11 11 11 11 11 11 11 11 11 11 11 11
The 3D vector can also be initialized by inserting the 2D vector one by one using vector push_back() method.
11 11 11 11 11 11 9 9 9 9 9 9
The 3D vector can also be initialized with another 3D vector by copying all elements with the help of copy constructor.
vector<vector<vector<int>>> v1(v2);
where v1 and v2 is the name of 3D vector.
1 2 3 4 5 6 7 8 9 10 11 12