std::bind 不适用于 std::sort
std::bind do not work with std::sort
为什么它仅在第二个参数大于 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_if
与std::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
的前面,您可以将partition
与greater_binded
一起使用。调用partition(begin(v), end(v), greater_binded)
会导致:
5 8 7 4 6 3 2 1
您还可以使用返回partition
更进一步
迭代到第二组的第一个元素
使用它来对第 1 组或第 2组进行排序或反向排序sort
.
相关文章:
- std::sort()函数无法对向量的一部分进行排序
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- C++中"std::sort"比较器的不同类型
- 将用户定义的类型与 std::vector 和 std::sort 一起使用
- 使用 std::sort 对向量进行稳定排序
- std::sort 如何处理重复的数字?
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- 使用 std::sort 对二维 c 数组进行排序
- std::stable_sort vs std::sort
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- std::vector 未按 std::sort 的预期排序
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 为什么只有当我的容器有超过 32 个元素时才由 std::sort 调用交换?
- 在 c++ 中使用 std::sort 与迭代器和模板
- 使用类似的比较函数时,在 c++ 中为 std:sort 获得不同的结果
- 相同的结果 qsort vs std::sort
- 通过 std::sort 对 C 2D 数组进行排序
- 对整个范围进行排序时,std::p artial_sort() 与 std::sort() 的性能?
- 在使用 std::sort() 和 lambda 函数按属性对 ADT 的向量进行排序时遇到问题
- 使用 std::sort 对矩阵进行排序