

Convert Set to a Vector during iteration in C++
source link: https://thispointer.com/convert-set-to-a-vector-during-iteration-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

This tutorial will discuss multiple ways to convert set to a vector during iteration in C++.
Table Of Contents
Advertisements
Using Range based for-loop
To convert a set into a vector during iteration, you can iterate over all the elements of the set one by one using a range-based for loop. For each element, utilize the push_back method of the vector to insert that element. By doing so, you can convert the set into a vector during iteration.
std::set<int> numbers = {11, 32, 43, 54, 55}; std::vector<int> vecObj; // Using range-based for loop to // append elements from set to vector for (const auto &num : numbers) { vecObj.push_back(num); }
Using std::copy() – STL ALgorithm
Another way to transform a set into a vector during iteration is by employing the std::copy() algorithm. For this method, you’ll provide three arguments:
- An iterator pointing to the start of the set.
- An iterator pointing to the end of the set.
- A back inserter, produced by the std::back_inserter function. This inserter can be used to append elements to the end of the vector.
std::set<int> numbers = {11, 32, 43, 54, 55}; std::vector<int> vecOfNumbers; // Using std::copy to append elements from set to vector std::copy( numbers.begin(), numbers.end(), std::back_inserter(vecOfNumbers));
Upon passing these three arguments to the std::copy algorithm, all the elements from the set will be inserted into the vector.
Let’s see the complete example,
#include <iostream> #include <set> #include <vector> int main() { std::set<int> numbers = {11, 32, 43, 54, 55}; std::vector<int> vecObj; // Using range-based for loop to // append elements from set to vector for (const auto &num : numbers) { vecObj.push_back(num); } // Display the vector for (const auto &num : vecObj) { std::cout << num << " "; } std::cout << std::endl; std::vector<int> vecOfNumbers; // Using std::copy to append elements from set to vector std::copy( numbers.begin(), numbers.end(), std::back_inserter(vecOfNumbers)); // Display the vector for (const auto &num : vecOfNumbers) { std::cout << num << " "; } std::cout << std::endl; return 0; }
Output
Summary
Today, we learned about convert set to a vector during iteration in C++.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK