Convert Set to a Vector during iteration in C++

This tutorial will discuss multiple ways to convert set to a vector during iteration in C++.

Table Of Contents

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

11 32 43 54 55 
11 32 43 54 55

Summary

Today, we learned about convert set to a vector during iteration in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top