In this article, we will discuss how to convert a list to a vector in C++.
Table Of Contents
Method 1: Using Range based constructor of vector
Pass the start, and end iterators of a list, to the vector constructor, while creating the vector object. It will create a vector object populated with the list contents. Let’s see an example,
#include <iostream> #include <vector> #include <list> template <typename T> void display(std::vector<T> vectorObj) { // Iterate over all elements of vector for(auto& elem : vectorObj) { std::cout<<elem << ", "; } std::cout<<std::endl; } int main() { std::list<int> listOfNumbers = {11, 12, 13, 14, 15, 16}; // Create a vector from list elements // using range constructor std::vector<int> vectorOfnumbers( listOfNumbers.begin(), listOfNumbers.end()); display(vectorOfnumbers); return 0; }
Output:
11, 12, 13, 14, 15, 16,
It converted the list to a vector.
Method 2: using vector::push_back()
Iterate over all the characters of a list using a range based for loop. During iteration, add each character to the vector using the member function push_back(). It accepts an element as an argument, and adds that to the end of vector. Let’s see an example,
#include <iostream> #include <vector> #include <list> template <typename T> void display(std::vector<T> vectorObj) { // Iterate over all elements of vector for(auto& elem : vectorObj) { std::cout<<elem << ", "; } std::cout<<std::endl; } int main() { std::list<int> listOfNumbers = {11, 12, 13, 14, 15, 16}; std::vector<int> vectorOfnumbers; // Iterate over all characters of list for (auto& elem : listOfNumbers) { // Add each character to vector vectorOfnumbers.push_back(elem); } display(vectorOfnumbers); return 0; }
Output:
Frequently Asked:
11, 12, 13, 14, 15, 16,
It converted the list to a vector.
Method 3: using STL Algorithm copy()
Pass two iterators pointing to the first, and one past the last element of list to the copy() function, as a range. Also, pass a back_insert_iterator of vector object to the copy() function. It will copy all the elements of list, to the vector. Let’s see an example,
#include <iostream> #include <vector> #include <list> #include <algorithm> template <typename T> void display(std::vector<T> vectorObj) { // Iterate over all elements of vector for(auto& elem : vectorObj) { std::cout<<elem << ", "; } std::cout<<std::endl; } int main() { std::list<int> listOfNumbers = {11, 12, 13, 14, 15, 16}; std::vector<int> vectorOfnumbers; // copy all elements of list to vector std::copy( listOfNumbers.begin(), listOfNumbers.end(), std::back_inserter(vectorOfnumbers)); display(vectorOfnumbers); return 0; }
Output:
Pointers in C/C++ [Full Course]
11, 12, 13, 14, 15, 16,
It converted the list to a vector.
Summary
We learned how to convert a list to a vector in C++.