根据向量元素的特征对向量进行排序
sorting a vector on its element's feature
首先,我要感谢到目前为止帮助过我的人。你真棒!!!!!(要是你知道就好了)
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
,并且应该被封装
相关文章:
- 将结构向量排序为子组
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 如何在对向量排序后更改索引值?c++
- C++向量排序给出0作为输出
- 将许多向量排序在一起
- 根据一个向量对多个向量排序
- 编译错误向量排序和联合
- C++我自己的函数进行向量排序
- 将字符串的向量排序为日期"yyyymmdd"
- C++ 通过使用旧向量进行预排序来改进向量排序
- C 向量排序 .h .cpp中的单独文件
- 向量排序-c++
- 将向量排序到一个无序映射c++11中
- 向量的向量排序
- c++向量排序方法编译失败,返回预期表达式
- 如何对bitset向量排序
- 向量排序的基础上只有先
- 我如何以相同的方式对两个向量排序,而条件只使用其中一个向量
- 列表排序和结构体向量排序之间的性能差距.c++
- 如何基于第二个字符串对字符串向量的向量排序