Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting struct using STL:algorithm

Tags:

c++

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??

like image 228
Devender Goyal Avatar asked Dec 28 '25 20:12

Devender Goyal


1 Answers

The std::sort algorithm takes 3 arguments:

  • Random-Access iterators to the initial position.
  • Random-Access iterators to the final position and
  • Sorting criteria

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.

like image 126
Alok Save Avatar answered Dec 31 '25 11:12

Alok Save