I was looking a way to sort struct using sort() function of STL:Algorithm library. I found a couple of codes using vector to do this. for example
struct person {
std::string name;
int age;
};
bool sort_by_name( const person & lhs, const person & rhs )
{
return lhs.name < rhs.name;
}
bool sort_by_age( const person & lhs, const person & rhs )
{
return lhs.age < rhs.age;
}
int main() {
std::vector<person> people;
// fill in the vector
std::sort( people.begin(), people.end(), sort_by_name );
std::sort( people.begin(), people.end(), sort_by_age );
}
I want to know is it possible to sort it without using vector.?? If yes then how??
The std::sort algorithm takes 3 arguments:
So as long as you have any type which can provide the initial and final iterators and you provide the sorting criteria, you can use std::sorton that type.
It is important though that sorting criteria has Strict Weak Ordering.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With