Home »
C++ STL
Create a vector and initialize it from another vector in C++ STL
C++ STL | vector creation and initialization from another vector: Here, we are going to learn how to create a vector and initialize it from another vector C++ STL?
Submitted by IncludeHelp, on May 12, 2019
What is the vector?
Vector is a container in C++ STL, it is used to represent array and its size can be changed.
Read more: C++ STL Vector
Create a vector and initializing it from another vector
We can also initialize a vector from a given vector in C++ STL. Here, we are going to learn the same, how can we initialize a vector from a given vector?
Here is the syntax to create and initialize and initialize vector from another vector,
vector<type> vector_name(another_vector.begin(), another_vector.end());
Here,
- type – is the datatype.
- vector_name – is any use defined name to the vector.
- another_vector.begin(), another_vector.end() – another vector's begin() and end() functions.
Example to create/declare and initialize vector from another vector
vector<int> v2(v1.begin(), v1.end());
C++ STL program to create and initialize a vector from another vector
//C++ STL program to create and initialize
//a vector from another vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//vector declaration and initialization
vector<int> v1{ 10, 20, 30, 40, 50 };
//vector declaration and initialization
//from given vector v1
vector<int> v2(v1.begin(), v1.end());
//printing the vector elements
//using for each kind of loop
cout << "Vector v2 elements are: ";
for (int element : v2)
cout << element << " ";
cout << endl;
return 0;
}
Output
Vector v2 elements are: 10 20 30 40 50