
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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.
- Related Articles
- Sorting a vector in C++
- Custom sorting using two different columns in MySQL?
- How to reverse a Vector using STL in C++?
- Perform custom sorting in MySQL
- How to find the maximum element of a Vector using STL in C++?
- How to find the sum of elements of a Vector using STL in C++?
- Custom sorting in list of tuples in Python
- Sorting a vector in descending order in C++
- How to sort a Vector in descending order using STL in C++?
- vector::begin() and vector::end() in C++ STL
- Find and print duplicate words in std::vector using STL functions using C++.
- Sorting objects by numeric values - JavaScript
- Sorting an array according to another array using pair in STL in C++
- vector insert() function in C++ STL
- C++ Program to Implement Sorting containers in STL

Advertisements