vectors are like dynamic arrays and they can be resized when an element is added or deleted. Their storage is handled automatically by the container. C++ allows multiple features which can help in merging two vectors efficiently. In this article, we will discuss six different ways to merge two vectors in C++.
Using merge() to merge two vectors in C++
In the C++ standard template library, there is a method merge()
which can be utilized to combine the elements of two containers in the sorted ranges. The resulting container is sorted in this method and this function is defined in the algorithm
header. There are two versions of this method. In the start one <
operator is used and a comparator (comp) for the second one for comparing the elements. Here we will use the start method of merge() function to merge two vector containers.
|
Syntax: __template <class in_iterator1, class in_iterator2, class out_iterator> out_iterator **merge** (in_iterator1 start1, in_iterator1 end1, in_iterator2 start2, in_iterator2 end2, out_iterator result); __ |
Parameters:
start1 & end1
: These are input iterators to the first and last positions of the first sorted container. It contains all the elements in the range [start, end), including the element pointed by the start1 and not the element pointed by the end1.
start2 & end2
: These are also input iterators to the first and last positions of the second sorted container.
result: It is an output iterator to store the sorted resulting elements.
Code
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 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; //Function to print vector void print_vector(vector<int> vector1) { for (int i = 0; i < vector1.size(); i++){ cout << vector1[i] << " "; } cout << "\n"; } int main() { // Get the vector vector<int> first = {10, 20}; vector<int> second = { 20, 30, 40, 50}; cout<<"First Vector Elements:"; print_vector(first); cout<< "Second Vector Elements: "; print_vector(second); //Declaring the new vector to store elements from both vectors vector<int> vect1(first.size() + second.size()); merge(first.begin(), first.end(), second.begin(), second.end(), vect1.begin()); cout<<"New Vector Elements using 'merge()': "; print_vector(vect1); return 0; } |
Output
First Vector Elements:10 20
Second Vector Elements: 20 30 40 50
New Vector Elements using ‘merge()’: 10 20 20 30 40 50
Using set_union() to merge two vectors in C++
set_union()
method of the standard template library can also be used to merge two containers in C++. It can also combine the two containers in the sorted ranges like merge()
. But, the resulting container after set_union() will only contain the elements that are present in both the containers only once and in merge(), the resulting container can contain the elements twice (keeping elements from both the ranges).
For example: A={10 , 20, 30, 50, 80} and B = {10, 20, 40};
Output for set_union
: C = {10, 20, 30, 40, 50, 80}
Output for merge
: D= { 10, 10, 20, 20, 30, 40, 50, 80}
set_union()
is also defined in the algorithm
header. There are two versions of this method. In the first version a comparison operator is used and a comparator is used for the second one. Here we will use only the first version of this function.
|
Syntax: __template <class in_iterator1, class in_iterator2, class out_iterator> out_iterator **set_union** (in_iterator1 start1, in_iterator1 end1, in_iterator2 start2, in_iterator2 end2, out_iterator result); __ |
Parameters:
start1 & end1
: These are input iterators to the first and last positions of the first sorted container. It contains all the elements in the range [start, end), including the element pointed by the start1 and not the element pointed by the end1.
start2 & end2
: These are also input iterators to the first and last positions of the second sorted container.
result
: It is an output iterator to store the sorted resulting elements.
Code
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 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; //Function to print vector void print_vector(vector<int> vector1) { for (int i = 0; i < vector1.size(); i++){ cout << vector1[i] << " "; } cout << "\n"; } int main() { // Get the vector vector<int> first = { 10, 20}; vector<int> second = { 20, 30, 40, 50}; cout<<"First Vector Elements:"; print_vector(first); cout<< "Second Vector Elements: "; print_vector(second); //Declaring the new vector to store elements from both vectors vector<int> vect1(first.size() + second.size()); set_union(first.begin(), first.end(), second.begin(), second.end(), vect1.begin()); cout<<"New Vector Elements using set_union(): "; print_vector(vect1); return 0; } |
Output
//0 in the end gets printed because one element(20) was common in both vectors
//we created vector of size of both vectors
//Iterator can be used in the for loop to print only valid elements in the new vector
First Vector Elements:10 20
Second Vector Elements: 20 30 40 50
New Vector Elements using set_union()
: 10 20 30 40 50 0
Using insert() to combine two vectors in C++
vector::insert() is an in-built function in the standard template library of C++. This function can be used to insert elements before the element at a specific position. We can utilize this function to merge two vectors in C++. In this method, we will use a copy constructor to initialize the second vector with the copy of all the elements of the first vector. Then, we will use the insert()
function to copy all the elements present in the second vector to the first vector. Elements present in both the vectors can also be directly copied in a new vector using the insert()
function.
|
Syntax(Using range): __template <class inp_iterator> void insert(iterator position, inp_iterator start, inp_iterator end);__ |
Parameters:
position
: New elements will be added to this position in the vector.
start and end
: They specify the input iterator position or range where elements will be inserted. The range includes the element which is pointed by the start variable and not the end variable.
Code
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 28 29 30 31 32 33 34 35 36 37
|
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; //Function to print vector void print_vector(vector<int> vector1) { for (int i = 0; i < vector1.size(); i++){ cout << vector1[i] << " "; } cout << "\n"; } int main() { //Creating two vectors to merge vector<int> first = { 10, 20}; vector<int> second = { 30, 40, 50}; //Using copy constructor and insert() vector<int> vect2(first); move(second.begin(), second.end(), back_inserter(vect2)); cout << "Vector Elements After Merge using Copy Constructor + insert(): "; print_vector(vect2); vect2.clear(); // Clearing the vector to use again //Using only insert() vect2.insert(vect2.begin(), first.begin(), first.end()); //Inserting 'first' elements in vect2 vect2.insert(vect2.end(), second.begin(), second.end()); //Inserting 'second' elements in vect2 cout << "Vector Elements After Merge using only insert(): "; print_vector(vect2); return 0; } |
Output
Vector Elements After Merge using Copy Constructor + insert(): 10 20 30 40 50
Vector Elements After Merge using only insert(): 10 20 30 40 50
Using move()
& back_inserter
to merge two vectors in C++
We can utilize the move() function to move the elements in the range [start, end). This function will add elements in the target container at the position pointed by the output iterator result. We will also use the back_inserter() function in this method to insert new elements at the end of the first vector. It is an output iterator that is made for allowing programs that need to overwrite elements at the end of the container. In this method, we can also merge two vectors using
- Copy constructor and both functions (move() & back_inserter())
- back_inserter() and move() function only
- move() function only
|
Syntax move(): __Output_Iterator move(Input_Iterator start, Input_Iterator end, Output_Iterator result); |
Parameters:
start, end
: They specify the input iterator position or range where elements will be inserted. The range includes the element which is pointed by the start variable and not the end variable.
result
: It marks the starting position for moving elements in the target container.
|
Syntax back_inserter: __template <class container> insert_iterator <container> back_inserter (container& a); Parameters: a: It represents the target container in which the elements will be inserted. |
Code
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; //Function to print vector void print_vector(vector<int> vector1) { for (int i = 0; i < vector1.size(); i++){ cout << vector1[i] << " "; } cout << "\n"; } int main() { //Creating two vectors to merge vector<int> first = { 10, 20}; vector<int> second = { 30, 40, 50}; //Using copy constructor and both functions vector<int> vect2(first); move(second.begin(), second.end(), back_inserter(vect2)); cout << "Vector Elements After Merge using move Constructor: "; print_vector(vect2); vect2.clear(); // Clearing the vector to use again //Using both move() and back_inserter() move(first.begin(), first.end(), back_inserter(vect2)); //move 'first' elements to vect2 move(second.begin(), second.end(), back_inserter(vect2));//move 'second' elements to vect2 cout << "Vector Elements After Merge using move() & back_inserter(): "; print_vector(vect2); vect2.clear(); // Clearing the vector to use again // 3. Using only move() function //Resizing the vect2 according to the size of 'first' and 'second' vect2.resize(first.size() + second.size()); move(first.begin(), first.end(), vect2.begin()); move(second.begin(), second.end(), vect2.begin() + first.size()); cout << "Vector Elements After Merge using move() only: "; print_vector(vect2); return 0; } |
Output
Vector Elements After Merge using move Constructor: 10 20 30 40 50
Vector Elements After Merge using move() & back_inserter(): 10 20 30 40 50
Vector Elements After Merge using move() only: 10 20 30 40 50
Using copy()
and back_inserter
to concatenate two vectors in C++
We can use the copy() in the same way we used the move() function. It can copy the elements in the specified range at the position given in the output iterator. This method will also contain the back_inserter()
method as an output iterator. The syntax remains the same as in the previous method, we just have to replace the move
with copy
. In this method also, we can also merge two vectors using
- Copy constructor and both functions (copy() & back_inserter())
- back_inserter() and copy() function only
- copy() function only
Code
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; //Function to print vector void print_vector(vector<int> vect1) { for (int i = 0; i < vect1.size(); i++){ cout << vect1[i] << " "; } cout << "\n"; } int main() { //Creating two vectors to merge vector<int> first = { 1, 2, 3, 4, 5}; vector<int> second = { 6, 7, 8, 9, 10 }; //Using copy constructor and both functions vector<int> vect2(first); copy(second.begin(), second.end(), back_inserter(vect2)); cout << "Vector Elements After Merge using Copy Constructor: "; print_vector(vect2); vect2.clear(); // Clearing the vector to use again //Using both copy() and back_inserter() copy(first.begin(), first.end(), back_inserter(vect2)); //Copy 'first' elements to vect2 copy(second.begin(), second.end(), back_inserter(vect2));//Copy 'second' elements to vect2 cout << "Vector Elements After Merge using copy() & back_inserter(): "; print_vector(vect2); vect2.clear(); // Clearing the vector to use again // 3. Using only copy() function //Resizing the vect2 according to the size of 'first' and 'second' vect2.resize(first.size() + second.size()); copy(first.begin(), first.end(), vect2.begin()); copy(second.begin(), second.end(), vect2.begin() + first.size()); cout << "Vector Elements After Merge using copy() only: "; print_vector(vect2); return 0; } |
Output
Vector Elements After Merge using move Constructor: 1 2 3 4 5 6 7 8 9 10
Vector Elements After Merge using move() & back_inserter(): 1 2 3 4 5 6 7 8 9 10
Vector Elements After Merge using move() only: 1 2 3 4 5 6 7 8 9 10
Using make_move_iterator()
and insert()
to merge two vectors in C++
This function make_move_iterator()
was introduced first in the C++ 11 version. This function returns move_iterator for the specified iterator iter
and the type will be deduced from the argument type.
Note: This method is different from move() & back_inserter
because the insert() function might allocate enough memory to store all the elements in a single allocation. But when we use back_inserter() that is equal to multiple push_back() which will do multiple allocations.
|
Syntax (C++ 11 - until C++ 17): __template <class Iterator> std::move_iterator <Iterator> make_move_iterator (Iterator i);__ Syntax (C++ 17 onwards): __template <class Iterator> constexpr std::move_iterator <Iterator> make_move_iterator (Iterator i);__ |
Parameters:
iter
is the input iterator that can be converted to a move iterator.
Code
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 28 29 30
|
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; void print_vector(vector<int> vect1) { cout<<"New Vector Elements After Merge: "; for (int i = 0; i < vect1.size(); i++){ cout << vect1[i] << " "; } } int main(int argc, char** argv) { vector<int> first = { 1, 2, 3 }; vector<int> second = { 4, 5, 6, 7, 8, 9, 10 }; //Moving elements from second vector to first vector first.insert( first.end(), make_move_iterator(second.begin()), make_move_iterator(second.end()) ); //Printing the vector print_vector (first); return 0; } |
Output
New Vector Elements After Merge: 1 2 3 4 5 6 7 8 9 10
Conclusion
We discussed several methods above which are efficient and can be used as per the requirements. It is easy to merge two vectors in C++ using any of the methods discussed above.
Happy Learning!!
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.