1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
struct Employee
{
std::string name;
std::string department;
int salary;
int id;
Employee(const std::string& n, const std::string& d, int s, int i)
: name(n), department(d), salary(s), id(i) {}
void Print() const
{
std::cout << "ID:" << id << " " << name << " (" << department << ") $" << salary;
}
};
void PrintEmployees(const std::vector<Employee>& employees, const std::string& title)
{
std::cout << title << ":" << std::endl;
for (const auto& emp : employees)
{
std::cout << " ";
emp.Print();
std::cout << std::endl;
}
std::cout << std::endl;
}
void StableSortExample()
{
std::cout << "=== Stable Sort Example ===" << std::endl;
std::vector<Employee> employees = {
{"Alice", "Engineering", 75000, 1},
{"Bob", "Marketing", 65000, 2},
{"Charlie", "Engineering", 75000, 3},
{"Diana", "Sales", 70000, 4},
{"Eve", "Engineering", 75000, 5},
{"Frank", "Marketing", 65000, 6}
};
PrintEmployees(employees, "Original");
// 先按部门排序
std::stable_sort(employees.begin(), employees.end(),
[](const Employee& a, const Employee& b) {
return a.department < b.department;
});
PrintEmployees(employees, "Sorted by Department (stable)");
// 再按薪水排序(保持部门内的原有顺序)
std::stable_sort(employees.begin(), employees.end(),
[](const Employee& a, const Employee& b) {
return a.salary > b.salary;
});
PrintEmployees(employees, "Sorted by Salary (stable) - maintains department order for same salary");
// 对比:使用普通sort
std::vector<Employee> employees2 = {
{"Alice", "Engineering", 75000, 1},
{"Bob", "Marketing", 65000, 2},
{"Charlie", "Engineering", 75000, 3},
{"Diana", "Sales", 70000, 4},
{"Eve", "Engineering", 75000, 5},
{"Frank", "Marketing", 65000, 6}
};
std::sort(employees2.begin(), employees2.end(),
[](const Employee& a, const Employee& b) {
return a.department < b.department;
});
std::sort(employees2.begin(), employees2.end(),
[](const Employee& a, const Employee& b) {
return a.salary > b.salary;
});
PrintEmployees(employees2, "Using regular sort - order may not be preserved");
}
int main()
{
StableSortExample();
return 0;
}
|