根据向量元素的特征对向量进行排序

sorting a vector on its element's feature

本文关键字:向量 排序 元素 特征      更新时间:2023-10-16

首先,我要感谢到目前为止帮助过我的人。你真棒!!!!!(要是你知道就好了)

typedef template<class T>struct 
{
   T homepet_;
   T wildpet_;
}Animal;
std::vector<Animal> va;
std::sort(va.begin(),va.end(),Pred<std::string>(sort_based_on_bool_and_arg));

我希望Pred(sort_based_on_bool_and_arg)用于基于
对向量进行排序1. 如果用户输入true,则为升序或降序,否则
2. 如果用户输入选择homepet_作为参数,那么它将对homepet_进行排序或者对wildpet_

进行排序

我相信你需要这样的东西:

struct functor
{
    inline bool operator()(const Animal& a, const Animal& b) const
    {
        return (does a come before b);
    }
};
typedef std::vector<Animal> va;
va list;
std::sort(list.begin(), list.end(), functor()); //call operator() on functor

我不知道Pred应该是什么,但我知道它不应该在那里。

sort在实现严格弱排序的向量的2个(引用)成员上取一个二元谓词。二元谓词既可以是函数,也可以是具有operator()的对象。如果您可以比较两个Animal对象,只需创建一个函数:

bool animal_less_than(const Animal &l, const Animal &r) { ... }

和调用sort:

std::sort(list.begin(), list.end(), &animal_less_than);

如果你需要一些额外的参数,你需要:

struct animal_less_than {
    type_of_extra_data extra_data;
    animal_less_than(type_of_extra_data extra_data) : extra_data(extra_data) {}
    bool operator()(const Animal &l, const Animal &r) { ... }
};

和调用sort:

std::sort(list.begin(), list.end(), animal_less_than(extra_data));

附带说明一下,声明Animal的语法是错误的。应该是:

template <typename T>
struct Animal {
    T homepet_;
    T wildpet_;
};

对于这个问题,它可能应该是class而不是struct,并且应该被封装