Sorting a vector of custom objects using C++ STL


You can sort a vector of custom objects using the C++ STL function std::sort. The sort function has an overloaded form that takes as arguments first, last, comparator. The first and last are iterators to first and last elements of the container. The comparator is a predicate function that can be used to tell how to sort the container. 

example

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;
struct MyStruct {
   int key;
   string data;
   MyStruct(int key, string data) {
      this -> key = key;
      this -> data = data;
   }
};
int main() {
   std::vector<MyStruct> vec;
   vec.push_back(MyStruct(4, "test"));
   vec.push_back(MyStruct(2, "is"));
   vec.push_back(MyStruct(3, "a"));
   vec.push_back(MyStruct(1, "this"));
   
   // Using lambda expressions in C++11
   sort(vec.begin(), vec.end(), [](const MyStruct& lhs, const MyStruct& rhs) {
      return lhs.key < rhs.key;
   });
   for(auto it = vec.begin(); it != vec.end(); it++) {
      cout << it -> data << endl;
   }
}

Output

This will give the output −

this is a test

If you're working on older C++ versions, you can pass a function reference as well −

//define the function:
bool comparator(const MyStruct& lhs, const MyStruct& rhs) {
   return lhs.key < rhs.key;
}
// pass it to sort:
sort(vec.begin(), vec.end(), &comparator);

You can also overload the < operator in the class/struct and use the sort(first, last) form directly. So when sorting, it will take this function to compare the items.


Updated on: 12-Feb-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements