Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set difference of two character sets C++

Tags:

c++

set

stl

Problem

I have two sorted sets:

set<char, greater<char> > alp1;
set<char, greater<char> > alp;

I need to find the set difference: alp-alp1:

Attempt 1

set_difference(alp.begin(), alp.end(), alp1.begin(), alp1.end(), inserter(diff1, diff1.end()));

But, only the first element of alp1 is subtracted from alp.

Attempt 2

itr = set_difference(alp.begin(), alp.end(), alp1.begin(), alp1.end(), diff1.begin());
for(auto it=diff.begin(); it<itr; it++)
   cout<<*it;

Attempt 2 Error:

no match for ‘operator<’ (operand types are ‘std::_Rb_tree_const_iterator<char>’ and ‘std::set<char>::const_iterator’ {aka ‘std::_Rb_tree_const_iterator<char>’})

How do I solve this problem?

like image 208
divya balakrishnan Avatar asked Nov 26 '25 02:11

divya balakrishnan


1 Answers

You need to pass a greater<char>() comparator to set_difference, the same comparator you use for your sets (see full API):

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

using namespace std;

int main() {
  set<char, greater<char>> alp = {'a', 'b', 'c', 'd', 'e'};
  set<char, greater<char>> alp1 = {'a', 'b', 'c'};
  set<char, greater<char>> diff;
  set_difference(alp.begin(), alp.end(), alp1.begin(), alp1.end(),
                 inserter(diff, diff.begin()), greater<char>());
  for (const char c : diff) {
    cout << c;
  }
  return 0;
}

Output:

ed

Demo: http://cpp.sh/3be2u.

like image 182
Yang Avatar answered Nov 27 '25 16:11

Yang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!