我搜索了很多,我不确定这个查询是否重复但我使用了 this作为为我的 std::vector
创建排序的引用,它采用以下类型的数据。
typedef struct {
int size;
int type;
int id;
} AC;
我能够为每个标准编写单独的函数对象。
但是,我的项目要求说我只需要一个类或结构来包含所有函数对象,以便根据 size
、type
和 id
。是否可以在一个类中包含 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/