Copying vector elements in a new vector
It is the method where we can insert the values of the existing vector into the newly created vector during Initialisation.
Syntax:
vector<vector<vector<int>>> v2(v1.begin(),v2.end());
Example:
vector<vector<vector<int>>> v1={ { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } }; // 3D vector original
vector<vector<vector<int>>> v2; // ( Copy elements of v1 inside v2 )
Code:
C++
#include <bits/stdc++.h> using namespace std; // function to display vector void display(vector<vector<vector< int > > >& v) { for ( int i = 0; i < v.size(); i++) { cout << "i : " << i << endl; 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; } cout << endl; } } int main() { vector<vector<vector< int > > > v = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; // initializing vect using v vector<vector<vector< int > > > vect(v.begin(), v.end()); display(vect); } |
i : 0 1 2 3 4 i : 1 5 6 7 8
Time Complexity: O(n)
Here n is the number of elements in the original vector.
Auxiliary Space: O(n)
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++.
Contact Us