 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements
 