Open In App

How to Initialize 3D Vector in C++ STL?

Last Updated : 30 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  1. Standard Initialization of a 3D vector
  2. Initialization of a 3D vector with given dimensions.
  3. 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++




// C++ program to initialise
// 3D vector using Standard
// initialization of a 3D vector
#include <iostream>
#include <vector>
 
using namespace std;
 
int main()
{
    // Initialising an empty 3D vector
    vector<vector<vector<int> > > v;
 
    // Adding values to the vector
    v.push_back({ { 1, 2, 3 }, { 3, 2, 1 } });
    v.push_back({ { 4, 5, 6 }, { 6, 5, 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;
}


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++




// 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;
}


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++




// C++ program to initialise
// 3D vector Initialization of
// 3D vector with some value
#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, 2)));
 
    // 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;
}


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 


Similar Reads

vector::at() and vector::swap() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::at() at() function is used reference the element present at the position given as the parameter to the function. Syntax: vectorname.at(position) Parameter
4 min read
vector :: cbegin() and vector :: cend() in C++ STL
Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. vector::cbegin() The function returns an iterator which is used to iterate container. The iterator points to the beginning of the vector.Iterator cannot modify the contents of the vector. Synta
2 min read
Initializing Vector using an Existing Vector in C++ STL
A vector is a type of container which can store objects of similar data type. Vector acts like a dynamic array where we can insert elements and the size of the array increases depending upon the elements inserted. Syntax: vector<data_structure/type> vector_name(size, item) To know more about vectors refer to vectors in C++. The 3D vector in C
5 min read
vector::operator= and vector::operator[ ] in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::operator=This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new
4 min read
vector::begin() and vector::end() in C++ STL
Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::begin()begin() function is used to return an iterator pointing to the first element of the vector container. begin() function returns a bidirectional
3 min read
vector::empty() and vector::size() in C++ STL
In C++, std::vector::size() and std::vector::empty() are the member functions of STL vector container. They are used provide the vector's size information. In this article, we will learn how to use vector::empty() and vector::size() in C++. Table of Content std::vector::empty()std::vector::size()vector::empty and vector::size() in C++ - FAQsstd::ve
2 min read
vector::front() and vector::back() in C++ STL
The vector::front() and vector::back() function in C++ STL are used to fetch the first and the last element of the std::vector container respectively. They are the member function of std::vector class and defined inside <vector> header file. In this article, we will learn about the vector::front() and vector::back() and how they are different
2 min read
vector::push_back() and vector::pop_back() in C++ STL
STL vector container provides two functions: push_back() and pop_back() for insertion and deletion from the end of the vector. In this article, we will learn discuss about these methods. vector::push_back()The push_back() function is used to push or insert an element into a vector at the back. It means that the new value is inserted into the vector
3 min read
7 ways to Initialize Vector in C++
Vectors in C++, like Arrays, are one of the most extensively used entities and to initialize vectors in C++ is one of the most common issues that users face. One of the most commonly used methods for vector initialization is the Array style. But C++, along with this, provides several different methods to initialize a vector. In this post, we have l
6 min read
Different Ways to Initialize a List in C++ STL
Prerequisite: List in C++ Lists are sequence containers that allow non-contiguous memory allocation The following are the different ways to create and initialize a List in C++ STL. Initializing an empty List and pushing values one by oneSpecifying List size and initializing all valuesInitializing List like the arraysInitializing a list from an arra
6 min read
vector::crend() & vector::crbegin() with example
These functions return useful iterators to access vector elements in reverse order (from end to beginning) Using vector::crend() It's a public member function that returns a const_reverse_iterator pointing to the element preceding the first element. Return Value A const_reverse_iterator to the reverse end of the sequence. Syntax: const_reverse_iter
2 min read
How to flatten a Vector of Vectors or 2D Vector in C++
Given a Vector of Vectors (2D vector), the task is to flatten this 2d vector. Examples: Input: vector = [[1, 2, 3, 4], [5, 6], [7, 8]] Output: 1 2 3 4 5 6 7 8 Input: vector = [[1, 2], [3], [4, 5, 6, 8]] Output: 1 2 3 4 5 6 8 Algorithm: 2D Vector can be flattened using iterators.Store starting and ending iterator of every vector in two arrays, iStar
2 min read
std::vector::resize() vs. std::vector::reserve()
In C++, vectors are dynamically resizable arrays provided by STL. They can automatically change their size according to the number of elements and users also can change its size using the std::vector::resize()and std::vector::reserve(). But there is some difference in how these functions works. In this article, we will learn what are the difference
5 min read
Is std::vector or boost::vector Thread Safe?
In C++, a common question that arises is: Is std::vector or boost::vector thread-safe? The straightforward answer is no, neither std::vector nor boost::vector is thread-safe. In this article, we will learn why std::vector and boost::vector are not thread-safe and explore some practical alternatives for making them safe to use in a multi-threaded en
5 min read
vector::emplace_back in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::emplace_back() This function is used to insert a new element into the vector container, the new element is added to the end of the vector. Syntax : vector
4 min read
vector rbegin() and rend() function in C++ STL
vector::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax: vector_name.rbegin() Parameters: The function does not accept any parameter.Return value: The function returns a reverse iterator pointing to the last element in the container.Program to demonstrate the vector::
2 min read
Copy File To Vector in C++ STL
Prerequisite: Vectors in C++ STLFile Handling in C++ The C++ Standard Template Library (STL) provides several useful container classes that can be used to store and manipulate data. One of the most commonly used container classes is the vector. In this article, we will discuss how to copy the contents of a file into a vector using C++ STL. Approach
2 min read
vector data() function in C++ STL
The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements. Syntax: vector_name.data() Parameters: The function does not accept any parameters.Return value: The function returns a pointer to the first element in the array which is used internally by the vecto
1 min read
vector emplace() function in C++ STL
The vector::emplace() is an STL in C++ which extends the container by inserting a new element at the position. Reallocation happens only if there is a need for more space. Here the container size increases by one.Syntax: template iterator vector_name.emplace (const_iterator position, element); Parameter: The function accepts two mandatory parameter
3 min read
vector max_size() function in C++ STL
The vector::max_size() is a built-in function in C++ STL which returns the maximum number of elements that can be held by the vector container. Syntax: vector_name.max_size() Parameters: The function does not accept any parameters. Return value: The function returns the maximum numbers that can fit into the vector container. Time Complexity - Const
1 min read
vector shrink_to_fit() function in C++ STL
The vector::shrink_to_fit() is a built-in function in C++ STL which reduces the capacity of the container to fit its size and destroys all elements beyond the capacity. Syntax: vector_name.shrink_to_fit() Parameters: The function does not accept any parameters. Return value: The function does not returns anything. Time Complexity - Linear O(N) Belo
2 min read
vector capacity() function in C++ STL
The vector::capacity() function is a built-in function which returns the size of the storage space currently allocated for the vector, expressed in terms of elements. This capacity is not necessarily equal to the vector size. It can be equal to or greater, with the extra space allowing to accommodate for growth without the need to reallocate on eac
2 min read
How to find common elements between two Vector using STL in C++?
Given two vectors, find common elements between these two vectors using STL in C++. Example: Input: vec1 = {1, 45, 54, 71, 76, 12}, vec2 = {1, 7, 5, 4, 6, 12} Output: {1, 12} Input: vec1 = {1, 7, 5, 4, 6, 12}, vec2 = {10, 12, 11} Output: {1, 4, 12} Approach: Common elements can be found with the help of set_intersection() function provided in STL.
2 min read
How to sort a Vector in descending order using STL in C++?
Given a vector, sort this vector in descending order using STL in C++. Example: Input: vec = {1, 45, 54, 71, 76, 12} Output: {76, 71, 54, 45, 12, 1} Input: vec = {1, 7, 5, 4, 6, 12} Output: {12, 7, 6, 5, 4, 1} Approach: Sorting can be done with the help of sort() function provided in STL. Syntax 1: sort(arr, arr + n, greater<T>()); C/C++ Code
2 min read
How to find the sum of elements of a Vector using STL in C++?
Given a vector, find the sum of the elements of this vector using STL in C++. Example:Input: vec = {1, 45, 54, 71, 76, 12} Output: 259 Input: vec = {1, 7, 5, 4, 6, 12} Output: 35Approach: Sum can be found with the help of accumulate() function provided in STL. Syntax:accumulate(first_index, last_index, initial value of sum); C/C++ Code // C++ progr
2 min read
Vector of Vectors in C++ STL with Examples
Prerequisite: Vectors in C++ STL Vectors are known as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector of Vectors is a two-dimensional vector with a variable number of rows where each row is vector. Each index of vector stor
5 min read
Create a balanced BST using vector in C++ STL
Given an unsorted vector arr, the task is to create a balanced binary search tree using the elements of the array. Note: There can be more than one balanced BST. Forming any is acceptable Examples: Input: arr[] = { 2, 1, 3}Output: 2 1 3Explanation: The tree formed is show below. The preorder traversal is 2 1 3 2 / \ 1 3 Input: arr[] = {4, 3, 1, 2}O
5 min read
Difference Between Size and Capacity of a Vector in C++ STL
In this article, we are going to study the difference between the size and capacity of a vector in C++ STL. The size of the vector is defined as the total number of elements present in the vector. Vector is a dynamic array so it changes with the user input, unlike the static arrays which we define with the subscript operators "[]" which remain cons
3 min read
C++ STL - Vector in Reverse Order
Prerequisite: Vectors in C++ A vector can be printed in reverse order with the following methods: By traversing in the backward direction using indexingBy traversing in the backward direction using begin() and end() functions in C++ STLBy traversing in the backward direction using rbegin() and rend() functions in C++ STL Examples: Input: vector = {
3 min read
Split String by Space into Vector in C++ STL
Prerequisite: Vector in C++String in C++ Split String By Space Into Vector In C++, so we need to insert every character into a vector of characters. Example: string s="Geeks for Geeks" // Splitting string based on space // final vector will be ["Geeks" ,"for","Geeks"] We have multiple methods to perform this operation: Using getline() methodUsing s
5 min read
Practice Tags :