std::bind 不适用于 std::sort

std::bind do not work with std::sort

本文关键字:std sort 适用于 bind 不适用      更新时间:2023-10-16

为什么它仅在第二个参数大于 3 时才有效。我该如何解决它? 如果我对copy_if做同样的事情,它就会起作用! 任务:检查函子 std :: 绑定的效果。尝试使用它来形成标准函子 std 的条件 :: 更大 ( 模块)。

#include <set>
#include <algorithm>
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <iterator>
#include <string>
#include <functional>
using namespace std;
template<typename T>
static void PrintVector(const std::vector<T> &v)
{
for (auto iterator = v.begin(); iterator != v.end(); ++iterator)
{
std::cout << *iterator << " ";
}
std::cout << std::endl;
}
int main()
{
std::cout << "Task_3: greater with std::bindn";
ostream_iterator<int> out_it(cout, " ");
vector<int> v = { 1, 8, 7, 4, 3, 6, 2, 5 };
PrintVector(v);
auto greater_binded = bind(greater<int>(), placeholders::_1, 3);
sort(v.begin(), v.end(), greater_binded);
PrintVector(v);
return 0;
}

std::copy_if文档中所述,它期望一元谓词即具有一个参数的函数,在另一侧std::sort需要比较函数,必须满足比较概念的要求。因此,完全不清楚为什么您期望使用相同的功能std::copy_ifstd::sort一起工作。

我该如何解决它?

只需传递std::greater<int>而不将第二个参数绑定到常量。如果你确实需要使用std::bind你可以只传递两个参数:

auto greater_binded = bind(greater<int>(), placeholders::_1, placeholders::_2);

但这与直接传递greater<int>()具有相同的效果。

sort的比较器要求是:

比较函数对象(即满足 Compare 要求的对象),如果第一个参数小于(即在第二个参数之前排序),则返回true

greater函子需要 2 个参数,但您正在使用bind将其变成一个函子,该函子需要 1 个参数并将其与3进行比较。这不再满足sort的要求。

如果您尝试将所有大于3的元素移动到v的前面,您可以将partitiongreater_binded一起使用。调用partition(begin(v), end(v), greater_binded)会导致:

5 8 7 4 6 3 2 1

您还可以使用返回partition更进一步

,即:

迭代到第二组的第一个元素

使用它来对第 1 组或第 2进行排序或反向排序sort.