Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there support in C++/STL for sorting objects by attribute?

Tags:

People also ask

Which sorting is used in STL?

In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By default, it uses QuickSort but if QuickSort is doing unfair partitioning and taking more than N*logN time, it switches to HeapSort and when the array size becomes really small, it switches to InsertionSort.

Is sort STL stable?

As of September 2020, it appears that libc++ std::sort happens to be stable for all ranges of size less than 31, and libstdc++ std::sort happens to be stable for all ranges of size less than 17. (Do not rely on this little factoid in production!)

Is STL sort in place?

Sort is an in-built function in a C++ STL ( Standard Template Library). This function is used to sort the elements in the range in ascending or descending order.

What is the complexity of STL sort?

Sort. The std::sort is a sorting function that uses the Introsort algorithm and have the complexity of O(N log(N)) where N= std::distance(first, last) since C++11 and the order of equal elements is not guaranteed to be preserved[3].


I wonder if there is support in STL for this:

Say I have an class like this :

class Person { public:   int getAge() const;   double getIncome() const;   ..   .. }; 

and a vector:

vector<Person*> people; 

I would like to sort the vector of people by their age: I know I can do it the following way:

class AgeCmp { public:    bool operator() ( const Person* p1, const Person* p2 ) const    {      return p1->getAge() < p2->getAge();    } }; sort( people.begin(), people.end(), AgeCmp() ); 

Is there a less verbose way to do this? It seems overkill to have to define a whole class just because I want to sort based on an 'attribute'. Something like this maybe?

sort( people.begin(), people.end(), cmpfn<Person,Person::getAge>() );