README
Custom Object Sorting in C++
Introduction
When working with primitive data types such as int, float, or string, the C++ sort() function can sort them automatically.
However, for custom objects (classes or structures), sort() does not know which property should be used for comparison.
To solve this problem, we use a Custom Comparator Function.
A comparator function tells sort():
- When two objects are already in the correct order.
- When two objects need to be swapped.
Student Class
class Student
{
public:
string name;
int roll;
int marks;
};
Each student contains:
| Property | Description |
|---|---|
| name | Student Name |
| roll | Roll Number |
| marks | Obtained Marks |
Sorting by Marks
Comparator Function
bool cmp(Student a, Student b)
{
return a.marks < b.marks;
}
Explanation
The comparator receives two student objects.
cmp(a, b)
If:
a.marks < b.marks
returns true, then a should appear before b.
Otherwise, sort() will rearrange them.
Sorting Call
sort(a, a + n, cmp);
Parameters
| Parameter | Meaning |
|---|---|
| a | Starting address |
| a + n | Ending address |
| cmp | Comparator function |
Multi-Level Sorting
Sometimes multiple students may have the same marks.
In that case:
- Sort by Marks (Ascending)
- If Marks are Equal → Sort by Roll (Ascending)
Comparator
bool cmp(Student a, Student b)
{
if (a.marks != b.marks)
return a.marks < b.marks;
return a.roll < b.roll;
}
Comparison Flow
Compare Marks
│
├── Different
│ │
│ └── Smaller Marks First
│
└── Equal
│
└── Compare Roll Numbers
│
└── Smaller Roll First
Example
Input
4
Rahim 10 85
Karim 5 90
Naim 2 85
Hasan 1 70
Output
Hasan 1 70
Naim 2 85
Rahim 10 85
Karim 5 90
Why?
- 70 comes before 85
- Two students have 85
- Roll 2 comes before Roll 10
Time Complexity
| Operation | Complexity |
|---|---|
| sort() | O(N log N) |
Best Practice
❌ Avoid
return a.marks <= b.marks;
✅ Use
return a.marks < b.marks;
std::sort() expects a strict comparison rule. Using <= may lead to undefined behavior.
Key Takeaways
- Use custom comparators to sort objects.
- Pass the comparator as the third parameter of
sort(). - Return
truewhen the current order is correct. - Multiple conditions can be applied inside a comparator.
std::sort()works in O(N log N) time.- Always use strict comparison (
<) whenever possible.
Author Notes
This example demonstrates how custom comparator functions allow powerful sorting logic for user-defined objects in C++.