C ++ comparison function set_intersection

When using functions in <algorithm>, there is usually one additional argument to customize the comparison. But I do not quite understand the description of this argument ( set_intersection documentation ).

A binary function that takes two type arguments specified by input iterators and returns a value convertible to bool. The return value indicates whether the first argument is considered to be the second in the particular strict weak order that it defines. a function must not change any of its arguments. It can be a function pointer or a function object.

It describes that a function should return the order of two arguments. But what about the matching function, for example:

#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);
}

We get the output:

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> , ?

+4
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

, , , , . :

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

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

...

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

bool func1 (int a, int b) { return a==b; }, bool func2 (int a, int b) { return a+b == 8; } , a b. , , "": , STL - , , a b, , - . :

bool func1 (int a, int b) { return a<b; }
bool func2 (int a, int b) { return a>b; }
+1

The comparison function provides sorting order. The default is std :: less and how to write such functions . If you want to keep the ascending sort order for integers, just keep the default value and do not specify any comparison function.

+1
source

Source: https://habr.com/ru/post/1599462/


All Articles