std::sort with std::pairs

Here’s an example of sorting a std::vector of std::pair<string, int> (representing student names and IDs) using a custom comparator implemented in a class:

#include <iostream>
#include <vector>
#include <algorithm> // for std::sort
using namespace std;

// Custom comparator class
class CompareByName {
public:
bool operator()(const pair<string, int> &a, const pair<string, int> &b) const {
return a.first < b.first; // Compare based on the student name (first element of the pair)
}
};

int main() {
// Vector of student names and IDs
vector<pair<string, int>> students = {
{"Alice", 1002},
{"Charlie", 1005},
{"Bob", 1001},
{"Eve", 1003}
};

// Sort the vector using the CompareByName comparator
sort(students.begin(), students.end(), CompareByName());

// Print the sorted list of students
cout << "Sorted Students (by name):" << endl;
for (const auto &student : students) {
cout << "Name: " << student.first << ", ID: " << student.second << endl;
}

return 0;
}

Output:

Sorted Students (by name):
Name: Alice, ID: 1002
Name: Bob, ID: 1001
Name: Charlie, ID: 1005
Name: Eve, ID: 1003

Explanation:

  1. Comparator Class:
    • The CompareByName class defines an operator() to act as a functor (function object).
    • This allows the class to behave like a callable function, making it usable in std::sort.
  2. Sorting Logic:
    • The comparison is done on the first element of the pairs (student names), which determines the sort order.
  3. Usage in std::sort:
    • An instance of CompareByName is passed to std::sort as the comparator.
  4. Result:
    • The students vector is sorted alphabetically by the student name while preserving the associated IDs.
Scroll to Top