Custom Comparator for Sorting
C++
Hard
3 views
Problem Description
Sort vector of pairs by second element.
Real Life: Sorting students by marks, not by name.
Step-by-Step Logic:
1. Create custom comparison function
2. Pass it to sort()
3. Define your own sorting logic
4. Sort by any criteria you want
Official Solution
bool compareBySecond(pair<string, int> a, pair<string, int> b) {
return a.second > b.second; // Descending order
}
void stl_q11_custom_sort() {
vector<pair<string, int>> students;
students.push_back(make_pair("Raj", 85));
students.push_back(make_pair("Priya", 92));
students.push_back(make_pair("Amit", 78));
sort(students.begin(), students.end(), compareBySecond);
cout << "Students sorted by marks:" << endl;
for(auto s : students) {
cout << s.first << " : " << s.second << endl;
}
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!