C++ set_intersection 比较函数

标签 c++ algorithm comparison

使用 <algorithm> 中的功能时, 通常有一个额外的参数来自定义比较。但是我不太明白关于参数的描述(Documentation of set_intersection)。

Binary function that accepts two arguments of the types pointed by the input iterators, and returns a value convertible to bool. The value returned indicates whether the first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object.

它描述了函数应该返回两个参数的顺序。但是在匹配函数中呢,例如:

#include <algorithm>
#include <iostream>

using namespace std;

void print (const char* name, int* start, int* end) {
    cout << name << ": ";
    while (start < end) 
        cout << *start++ << ", ";
    cout << endl;
}

bool func1 (int a, int b) { return a==b; }
bool func2 (int a, int b) { return a+b == 8; }

int main() {
  int set1[6] = {0, 1, 2, 4, 2, 4};
  int set2[6] = {1, 2, 3, 4, 5, 6};

  int set_without_comp[6];
  int* end_wo = set_intersection(set1, set1+6, set2, set2+6, set_without_comp);
  print ("set_without_comp", set_without_comp, end_wo);

  int set_with_comp1[6];
  int *end_w1 = set_intersection(set1, set1+6, set2, set2+6, set_with_comp1, func1);
  print ("set_with_comp1", set_with_comp1, end_w1);

  int set_with_comp2[6];
  int *end_w2 = set_intersection(set1, set1+6, set2, set2+6, set_with_comp2, func2);
  print ("set_with_comp2", set_with_comp2, end_w2);
}

我们得到输出:

set_without_comp: 1, 2, 4, 
set_with_comp1: 0, 1, 2, 2, 4, // Expect 1, 2, 4, 
set_with_comp2: 0, 1, 2, 2, 4, // Expect 2, 4, (maybe 6)

如何解释结果,以及在使用 <algorithm> 时编写比较函数的正确方法是什么?函数,以及如何编写一个可以给我预期结果的函数?

最佳答案

std::set_intersection 需要一个函数,该函数以两个元素存储在集合中的相同方式关联两个元素。它不是描述哪些元素相同的函数,因为该函数在内部执行此操作。

因此,在您的示例中,set1 不是正确的集合,因为它没有按顺序排列(例如,升序)。如果它是有序的,您可以在 std::set_intersection 中使用相同的顺序函数。例如:

int set1[6] = {0, 1, 2, 2, 2, 4}; // in order (<)

bool func1 (int a, int b) { return a < b; } // the only valid function

在处理没有隐含顺序的复杂对象时,明确说明要使用的排序函数的功能非常有用。例如:

struct Person {
  std::string name;
  int age;
};

bool ascendingAge(const Person& guy1, const Person& guy2) {
  return guy1.age < guy2.age;
}

...

std::intersection(..., ..., ascendingAge);

关于C++ set_intersection 比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31605306/

相关文章:

c++ - 从 GMock 获得失败的期望

c - 在c中递归查找数组的第三大元素

python - Smalltalk(例如 Pharo)与 Python 相比如何?

php - 通过 > 和 < 运算符比较日期

database - Prolog 数据库查询

c++ - 在我的教科书上看不懂这个素数生成器算法

c++ - 不安全的模板数组构造函数

algorithm - 计算大 n 的快速算法! mod 2³²

c++ - 从剪影中提取最外层轮廓

c# - 如何在 C# 中编写线性同余生成器 (LCG)?或者有什么众所周知的实现吗?