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:
- Comparator Class:
- The
CompareByNameclass defines anoperator()to act as a functor (function object). - This allows the class to behave like a callable function, making it usable in
std::sort.
- The
- Sorting Logic:
- The comparison is done on the
firstelement of the pairs (student names), which determines the sort order.
- The comparison is done on the
- Usage in
std::sort:- An instance of
CompareByNameis passed tostd::sortas the comparator.
- An instance of
- Result:
- The
studentsvector is sorted alphabetically by the student name while preserving the associated IDs.
- The
