c ++ set_intersection比较函数

Pan*_*ang 5 c++ algorithm comparison

使用函数时<algorithm>,通常会有一个额外的参数来自定义比较.但我不太了解有关参数的描述(set_intersection的文档).

二进制函数,它接受输入迭代器指向的两个类型的参数,并返回一个可转换为bool的值.返回的值指示第一个参数是否在其定义的特定严格弱顺序中被认为是在第二个参数之前.该函数不得修改其任何参数.这可以是函数指针或函数对象.

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

#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);
}
Run Code Online (Sandbox Code Playgroud)

我们得到输出:

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)
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*ger 3

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
Run Code Online (Sandbox Code Playgroud)

当您处理没有隐式顺序的复杂对象时,明确说明要使用什么顺序函数的能力非常有用。例如:

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

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

...

std::intersection(..., ..., ascendingAge);
Run Code Online (Sandbox Code Playgroud)