一:功能
对区间内元素进行排序,保证相等元素的顺序(稳定排序)
二:用法
#include <iostream>
struct Record {
std::string label;
int rank;
};
int main() {
std::vector<Record> data {{"q", 1}, {"f", 1}, {"c", 2}, {"a", 1}, {"d", 3}};
std::ranges::stable_sort(data, {}, &Record::label);
std::ranges::stable_sort(data, {}, &Record::rank);
for (auto &v : data) {
std::cout << v.label << "-" << v.rank << " ";
}
std::cout << "\n";
}
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <vector>
struct Employee
{
int age;
std::string name; // Does not participate in comparisons
};
bool operator<(const Employee& lhs, const Employee& rhs)
{
return lhs.age < rhs.age;
}
#if __cpp_lib_constexpr_algorithms >= 202306L
consteval auto get_sorted()
{
auto v = std::array{3, 1, 4, 1, 5, 9};
std::stable_sort(v.begin(), v.end());
return v;
}
static_assert(std::ranges::is_sorted(get_sorted()));
#endif
int main()
{
std::vector<Employee> v{{108, "Zaphod"}, {32, "Arthur"}, {108, "Ford"}};
std::stable_sort(v.begin(), v.end());
for (const Employee& e : v)
std::cout << e.age << ", " << e.name << '\n';
}