JanW
JanW

Reputation: 113

How to convert std::set to std::array?

I have std::set and I need to convert it to std::array. Order of elements doesn't matter.

The opposite conversion seems to be simple, because I can just do:

std::array<T> array;
std::set<T> set(array.begin(), array.end());

But unfortunately std::array doesn't have constructor like this, so I'm unable to do:

std::set<T> set;
std::array<T> array(set.begin(), set.end());

What's the proper way of such conversion?

Upvotes: 2

Views: 8665

Answers (1)

catnip
catnip

Reputation: 25388

As mentioned in the comments above, std::array is not suitable for this as the size must be known at compile time. std::vector is an appropriate substitute.

Here's one way to populate a vector from a set. It should be straightforward to convert this to a template. Note the use of reserve for efficiency:

#include <iostream>
#include <set>
#include <vector>
#include <algorithm>

int main()
{
    std::set <int> s = { 1, 2, 3, 4, 5 };
    std::vector <int> v;
    v.reserve (s.size ());
    std::copy (s.begin (), s.end (), std::back_inserter (v));
    for (auto i : v)
        std::cout << i << '\n';
}

Live demo

Upvotes: 5

Related Questions