设置两个字符集C ++的差异

问题描述 投票:4回答:1

Problem

我有两个排序集:

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

我需要找到设定的差异:alp-alp1:

Attempt 1

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

但是,只有alp1的第一个元素从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>’})

我该如何解决这个问题?

c++ stl set
1个回答
6
投票

您需要将greater<char>()比较器传递给set_difference,这是您用于集合的相同比较器(请参阅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;
}

输出:

ed

但是:ku zxsw。

© www.soinside.com 2019 - 2024. All rights reserved.