suppose we have a
vector<student> allstudent
Now I would like to sort the students using different memebers,such as name, age, address, like that.
How can I do that?
suppose we have a
vector<student> allstudent
Now I would like to sort the students using different memebers,such as name, age, address, like that.
How can I do that?
Create a functor to compare the correct field, then specify the functor when you sort:
struct by_age {
bool operator()(student const &a, student const &b) const {
return a.age < b.age;
}
};
struct by_name {
bool operator()(student const &a, student const &b) const {
return a.name < b.name;
}
};
// sort by age
std::sort(students.begin(), students.end(), by_age());
// sort by name
std::sort(students.begin(), students.end(), by_name());
These are two easy ways:
bool operator <(const student &lhs, const student &rhs)
{
return lhs.age < rhs.age;
}
std::sort(allstudent.begin(), allstudent.end()); // sorts by age
Or write a compare function:
bool cmp(const student &lhs, const student &rhs)
{
return lhs.age < rhs.age; // here go your sort conditions
}
std::sort(allstudent.begin(), allstudent.end(), cmp); // also sorts by age
in general, boost::multi_index provides a lot of this functionality. This comes in especially useful if you need rapid access on more than one key. This answer won't help you with your homework though ;-) See http://www.boost.org/
In addition to earlier comments, you can also define multidimensional filters, like this:
bool operator <(const student &a, const student &b)
{
return ((a.age < b.age) ||
((a.name < b.name) && (a.age == b.age)) ||
((a.address <= b.address) && (a.name == b.name) && (a.age == b.age)))
}
Just like the operator above, you can make more advanced filters if needed.