To create a three-dimensional vector in C++, you can use nested vectors.
In this example,
#include <iostream>
#include <vector>
int main() {
// Step 1: Create a numeric three-dimensional vector
std::vector<std::vector<std::vector<int>>> three_dimensional_vector = {
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},
{{10, 11, 12}, {13, 14, 15}, {16, 17, 18}},
{{19, 20, 21}, {22, 23, 24}, {25, 26, 27}}
};
// Step 2: Print the vector
for (const auto& layer : three_dimensional_vector) {
for (const auto& row : layer) {
for (int element : row) {
std::cout << element << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
In this example,
#include <iostream>
#include <vector>
#include <string>
int main() {
// Step 1: Create a string three-dimensional vector
std::vector<std::vector<std::vector<std::string>>> three_dimensional_vector = {
{ {"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"} },
{ {"j", "k", "l"}, {"m", "n", "o"}, {"p", "q", "r"} },
{ {"s", "t", "u"}, {"v", "w", "x"}, {"y", "z", "!"} }
};
// Step 2: Print the vector
for (const auto& layer : three_dimensional_vector) {
for (const auto& row : layer) {
for (const auto& element : row) {
std::cout << element << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
return 0;
}
a b c d e f g h i j k l m n o p q r s t u v w x y z !
In this tutorial, we learned How to create a Three Dimensional Vector in C++ language with well detailed examples.