Open In App

How to Merge Multiple Vectors into a List in C++?

Last Updated : 13 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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


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




Next Article
Practice Tags :

Similar Reads