How to Initialize 3D Vector in C++ STL?
Last Updated :
30 Nov, 2022
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.
3-D Vector
A 3D vector is a type of vector having 3 Dimensions means a vector storing a 2-D vector inside it, similar to a 2-D array.
There are a few methods to initialize a 3D vector these are:
- Standard Initialization of a 3D vector
- Initialization of a 3D vector with given dimensions.
- Initialization of a 3D vector with some value
1. Standard Initialization of a 3D vector
Standard initialization of a 3D vector is a method where we initialize by declaring and then inserting elements using the push_back( ) function.
Syntax:
vector<vector<vector<data_type>>> vector_name;
Example:
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector<vector< int > > > v;
v.push_back({ { 1, 2, 3 }, { 3, 2, 1 } });
v.push_back({ { 4, 5, 6 }, { 6, 5, 4 } });
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;
}
|
Output
1 2 3
3 2 1
4 5 6
6 5 4
2. 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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector<vector< int > > > v(
2, vector<vector< int > >(3, vector< int >(4)));
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;
}
|
Output
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
3. Initialization of a 3D vector with some value
Initialization of 3D vector with some value in this method we are creating a vector with x,y, and z dimensions with some value inside it.
Syntax:
vector<vector<vector<data_type>>> vector_name(x, vector<vector<data_type>>(y, vector<data_type>(z,value)));
Example:
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector<vector< int > > > v(
2, vector<vector< int > >(3, vector< int >(4, 2)));
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;
}
|
Output
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
Share your thoughts in the comments
Please Login to comment...