Home > Software engineering >  using set_union() with a lambda
using set_union() with a lambda

Time:07-26

I would like to use set_union() and just scan the output without having to store it.

Something like this (it doesn't compile using g 12.1.0):

#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;

int main()
{
    vector<int> a = {1,2,3}, b={4,5,6};
    ranges::set_union(a, b, [](int i){printf("%d,",i);});
}

CodePudding user response:

You need to supply an "output iterator" for set_union() to pass elements to. It does not accept a lambda (or other callable type). You can use std::ostream_iterator for this, eg:

#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
// ...
vector<int> a = {1,2,3}, b={4,5,6};
ranges::set_union(a, b, std::ostream_iterator<int>(std::cout, ","));
  • Related