【发布时间】:2015-07-24 16:21:37
【问题描述】:
在使用<algorithm> 中的函数时,通常有一个额外的参数来自定义比较。但是我不太明白关于论点的描述(Documentation of 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);
}
我们得到输出:
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::less<T>之类的参数——基本上是operator<,就像所有其他对排序进行操作的算法一样。 -
@Konrad Rudolph 但有时我不需要顺序,我只需要匹配元素,就像我在帖子中写的那样,
set_intersection应该在两者中找到匹配的元素集,而不是订单。 -
在 C++ 标准算法中,所有这些都是通过排序来表达的(因为这有助于有效地实现集合操作)。如果两个元素都不大于另一个,则两个元素相等。
-
不确定,但我认为您应该提供总订单功能。
-
如果您认为您的问题已得到解决,请选择一个答案作为解决方案。
标签: c++ algorithm comparison