Jan Schultke
Jan Schultke

Reputation: 39588

Is there a view in std::views or range-v3 for set operations? If not, how do I make my own?

It would be convenient if I had a view which lets me examine the result of a set operation. This is similar to std::set_union, std::set_difference, and std::set_intersection; however, it should not require modification or output into a new range.

Desired usage
int a[] {1, 2, 4, 8, 16};
int b[] {1, 8, 80};
auto i = views::set_intersection(a, b); // {1, 8}
auto u = views::set_union(a, b);        // {1, 2, 4, 8, 16, 80}
auto d = views::set_difference(a, b);   // {2, 4, 16}

// note: the following syntax should also work, like for all views:
//       a | views::set_xyz(b)

Does such a thing exist in the standard library of any standard or perhaps in range-v3? If not, how do I make my own?

Upvotes: 1

Views: 195

Answers (1)

TemplateRex
TemplateRex

Reputation: 70526

Yes, this currently works using range-v3:

#include <range/v3/view/set_algorithm.hpp>      // set_difference, set_intersection, set_symmetric_difference, set_union
#include <fmt/ranges.h>                         // println

int main()
{
    int a[] {1, 2, 4, 8, 16};
    int b[] {1, 8, 80};
    auto i = ranges::views::set_intersection(a, b);         fmt::println("{}", i);  // [1, 8]
    auto u = ranges::views::set_union(a, b);                fmt::println("{}", u);  // [1, 2, 4, 8, 16, 80]
    auto d = ranges::views::set_difference(a, b);           fmt::println("{}", d);  // [2, 4, 16]
    auto s = ranges::views::set_symmetric_difference(a, b); fmt::println("{}", s);  // [2, 4, 16, 80]        
}

Godbolt link

The WG21 paper p2760r1 puts this in Tier 3 (the lowest priority) for C++26 however.

Please also note that a view will not preserve the "set-ness" for formatting

Upvotes: 1

Related Questions