在使用<algorithm>中的函数时,通常有一个额外的参数来自定义比较。但是我并不完全理解关于这个论点的描述(交叉点)。
二进制函数,它接受输入迭代器指出的两个类型的参数,并返回一个可转换为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>函数编写比较函数的正确方法是什么,以及如何编写能够给出预期结果的比较函数?
发布于 2015-07-24 08:17:40
std::set_intersection期望一个将两个元素以相同的方式存储在集合中的函数。它不是一个函数来描述哪些元素是相同的,因为这个函数在内部工作。
因此,在您的示例中,set1不是一个合适的集合,因为它没有按顺序排列(例如,升序)。如果它是正确的,那么您可以在std::set_intersection中使用相同的order函数。例如:
int set1[6] = {0, 1, 2, 2, 2, 4}; // in order (<)
bool func1 (int a, int b) { return a < b; } // the only valid function在处理不具有隐式顺序的复杂对象时,显式说明要使用的order函数的能力非常有用。例如:
struct Person {
std::string name;
int age;
};
bool ascendingAge(const Person& guy1, const Person& guy2) {
return guy1.age < guy2.age;
}
...
std::intersection(..., ..., ascendingAge);发布于 2015-07-24 08:19:50
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; }发布于 2015-07-24 08:20:18
比较函数提供排序顺序。缺省值为std::less,这里是如何编写这样的函数。如果要保持整数的升序排序顺序,只需保留默认值,而不指定任何比较函数。
https://stackoverflow.com/questions/31605306
复制相似问题