C++ 标准 :sort() using different criteria

标签 c++ stl function-object

我搜索了很多,我不确定这个查询是否重复但我使用了 this作为为我的 std::vector 创建排序的引用,它采用以下类型的数据。

typedef struct {
    int size;
    int type;
    int id;
} AC; 

我能够为每个标准编写单独的函数对象。 但是,我的项目要求说我只需要一个类或结构来包含所有函数对象,以便根据 sizetypeid。是否可以在一个类中包含 std::sort 的所有函数对象?

我的意思是类似

Comparator com;
sort(iVec.begin(),iVec.end(),com.sortbysize);
sort(iVec.begin(),iVec.end(),com.sortbytype);
sort(iVec.begin(),iVec.end(),com.sortbyid);

我还查看了 binary_functions 来满足我的要求,但是当我在一个类中声明多个函数对象时,我遇到了错误。

此外,std::sort(以及任何涉及比较的 STL 算法)的函数对象是否必须是 bool operator() 或它们可以是返回 bool 的普通函数吗?

最佳答案

两者都是:

struct Comparator
{
    static bool sortbysize(const AC &lhs, const AC &rhs) { /*...*/ }
    static bool sortbytype(const AC &lhs, const AC &rhs) { /*...*/ }
    static bool sortbyid(const AC &lhs, const AC &rhs) { /*...*/ }
}

关于C++ 标准 :sort() using different criteria,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12965300/

相关文章:

c++ - 如何在不重建数组的情况下将 vector<vector<int>> 转换为 int**?

c++ - 当明确给出数字时,我是否应该引用 std::vector size

c++ - Qt:当QPointer改变时发出信号

c++ - 将命令行参数传递给从 C++ 程序调用的 bash shell 脚本

c++ - 如果传递的指针为空,placement new 是否会调用构造函数?

c++ - 如何将 std::function 分配给 C++ 中的运算符?

c++ - 为什么函数对象应该是按值传递的

c++ - 如何用 doxygen 记录一个函数对象?

java - BackgroundSubtractorMOG2 中的 "history"是什么意思?

c++ - 如何找到未知整数类型的最大值