How to Convert a Vector to a List Without Losing Element Order in C++?
In C++, vectors are dynamic arrays that store data in contiguous memory locations whereas lists are sequence containers that store data in non-contiguous memory locations. In this article, we will learn how to convert a vector to a list without losing the order of elements in C++.
Example:
Input:
myVector = {1, 2, 3, 4, 5};
Output:
myList = {1, 2, 3, 4, 5};
Converting a std::vector to a std::list in C++
To convert a std::vector to a std::list while preserving the order of the vector elements in the list, we can use the list constructor provided by the STL that takes the std::vector::begin() and std::vector::end() iterators and generates a list by preserving the order of the elements.
C++ Program to Convert a Vector to a List Without Losing Element Order
The following program illustrates how we can convert a vector to a list without losing the order of the elements of the vector.
// C++ Program to illustrate how to convert a vector to a
// list without losing the order of the elements
#include <iostream>
#include <list>
#include <vector>
using namespace std;
int main()
{
// Initialize a vector
vector<int> myVector = { 1, 2, 3, 4, 5 };
// Convert the vector to a list
list<int> myList(myVector.begin(), myVector.end());
// Print the list
for (auto& element : myList) {
cout << element << ", ";
}
cout << endl;
return 0;
}
Output
1, 2, 3, 4, 5,
Time Complexity: O(N), where N is the size of the vector.
Auxiliary Space: O(N)
Contact Us