How to Merge Multiple Vectors into a List in C++?
Last Updated :
13 Feb, 2024
In C++, a list is a not contiguous data storage container that implements the linked lists and a vector is a contiguous data storage container that implements dynamic arrays that can resize according to the need. In this article, we will learn how to merge multiple vectors into a single list in C++.
Input:
vector<int> vec1 = {1, 2, 3};
vector<int> vec2 = {4, 5, 6};
vector<int> vec3 = {7, 8, 9};
Output:
Elements in a list after merging: 1 2 3 4 5 6 7 8 9
Merge Multiple Vectors into a List in C++
To merge multiple vectors into a single list, we can use std::map::insert() which allows us to insert the range of elements in the list. It is the member function of the std::list container that takes the iterator to the beginning and the iterator to the end of the range and inserts all the elements in that range into its list.
C++ Program to Merge Multiple Vectors into a Single List
C++
#include <iostream>
#include <list>
#include <vector>
using namespace std;
int main()
{
vector< int > vec1 = { 1, 2, 3 };
vector< int > vec2 = { 4, 5, 6 };
vector< int > vec3 = { 7, 8 };
list< int > myList;
myList.insert(myList.end(), vec1.begin(), vec1.end());
myList.insert(myList.end(), vec2.begin(), vec2.end());
myList.insert(myList.end(), vec3.begin(), vec3.end());
cout << "Elements in Merged List: " << endl;
for ( auto i : myList)
cout << i << " " ;
cout << endl;
return 0;
}
|
Output
Elements in Merged List:
1 2 3 4 5 6 7 8
Time Complexity: O(N)
Auxiliary Space: O(N)
We can also use std::copy() with back_inserter() to merge multiple vectors into a single list in C++.
Share your thoughts in the comments
Please Login to comment...