Is one-line initialization of a <set> possible with C++20 <ranges>?

Viewed 139

I would like to know if with <ranges> in C++20 it is finally possible to select from a sequence and initialize a set in one line, as is possible in C# with IEnumerable. This would probably require converting a <ranges> object to a std::initializer_list.

C#:

int[] sequence = new int[] { 0,1,2,3,4 };
HashSet<int> set = new HashSet<int>(sequence.Where((int i) => i % 2 == 0));

C++:

std::vector<int> sequence { 0,1,2,3,4 };
auto matcher = sequence | std::ranges::views::filter([](int i) { return !(i % 2); });
std::set<int> myset(matcher.begin(), matcher.end());

I want to do something like:

std::vector<int> sequence { 0,1,2,3,4 };
std::set<int> myset { sequence | std::ranges::views::filter([](int i) { return !(i % 2); }) };
1 Answers

Actually, it is not possible for now, but in near future, we can get ranges::to which will have such functionality.

Related