Initialization of a 3D vector with given dimensions
Given below is the syntax for initializing the 3D vector with a given size in C++. The initialized value is 0 by default and thus different values can be assigned by traversing through loops.
Syntax:
vector<vector<vector<data_type>>> vector_name(x, vector<vector<data_type>>(y, vector<data_type>(z)));
Here x, y, and z are dimensions.
Example:
C++
// C++ program to initialise // 3D vector Initialization // of a 3D vector with // given dimensions #include <iostream> #include <vector> using namespace std; int main() { // Initialising a 3D vector with 0 as initial value vector<vector<vector< int > > > v( 2, vector<vector< int > >(3, vector< int >(4))); // Printing the 3d vector for ( int i = 0; i < v.size(); i++) { for ( int j = 0; j < v[i].size(); j++) { for ( int k = 0; k < v[i][j].size(); k++) { cout << v[i][j][k] << " " ; } cout << endl; } } return 0; } |
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
How to Initialize 3D Vector in C++ STL?
Prerequisite: Vector in C++
Vectors in C++ are the same as arrays with dynamic sizes having the ability to resize themselves, we can insert and remove elements from the end.