Reputation: 181
First, I would like to thank people for having helped me so far. You are great!!!!! (if only you knew it)
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));
I would like Pred(sort_based_on_bool_and_arg) used to sort vector based on
1. if user inputs true it is ascending or descending otherwise
2. if user inputs choose homepet_ as argument then it sorts for homepet_ or it will sort wildpet_
Upvotes: 1
Views: 148
Reputation: 63250
I believe you need something along these lines:
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
Upvotes: 2
Reputation: 76316
I don't know what Pred
is supposed to be, but I do know it shouldn't be there.
sort
takes a binary predicate on 2 (references to) members of the vector implementing strict weak ordering. A binary predicate can be either a function or an object with operator()
. If you can compare two Animal
objects, just create a function:
bool animal_less_than(const Animal &l, const Animal &r) { ... }
and call sort like:
std::sort(list.begin(), list.end(), &animal_less_than);
If you need some extra parameter, you'll need:
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) { ... }
};
and call sort like:
std::sort(list.begin(), list.end(), animal_less_than(extra_data));
On a side note, the syntax declaring Animal is wrong. It should be:
template <typename T>
struct Animal {
T homepet_;
T wildpet_;
};
and for the matter, it should probably be a class
rather than struct
and should be encapsulated.
Upvotes: 1