Sorting a vector of custom objects using C++ STL

C++Server Side ProgrammingProgramming

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. 



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;


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.

Published on 28-Feb-2018 10:31:20