C++ STL stable_sort用法

一:功能

      对区间内元素进行排序,保证相等元素的顺序(稳定排序)

二:用法

#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';
}

相关推荐

  1. new Promise

    2024-07-14 11:22:01       44 阅读
  2. qt 定时器

    2024-07-14 11:22:01       56 阅读
  3. fmt

    2024-07-14 11:22:01       52 阅读
  4. not exists

    2024-07-14 11:22:01       54 阅读
  5. 详解WebMvcConfigurer

    2024-07-14 11:22:01       37 阅读
  6. Tinyxml基本

    2024-07-14 11:22:01       58 阅读
  7. man

    2024-07-14 11:22:01       51 阅读
  8. mybatisPlus 常见

    2024-07-14 11:22:01       41 阅读
  9. v-show

    2024-07-14 11:22:01       54 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 11:22:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 11:22:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 11:22:01       58 阅读
  4. Python语言-面向对象

    2024-07-14 11:22:01       69 阅读

热门阅读

  1. Nikto 扫描 Web 服务器漏洞

    2024-07-14 11:22:01       24 阅读
  2. 优化实战篇—自关联的优化

    2024-07-14 11:22:01       18 阅读
  3. todolist-原生js(ES6)

    2024-07-14 11:22:01       22 阅读
  4. 日常学习--docker命令梳理--20240714

    2024-07-14 11:22:01       25 阅读
  5. iOS热门面试题(四)

    2024-07-14 11:22:01       26 阅读
  6. 56. 合并区间

    2024-07-14 11:22:01       23 阅读
  7. 微服务架构,通信协议,Web服务器和kafka

    2024-07-14 11:22:01       19 阅读
  8. 【学习笔记】Redis学习笔记——第9章 数据库

    2024-07-14 11:22:01       25 阅读
  9. 基于gunicorn+flask+docker模型高并发部署

    2024-07-14 11:22:01       22 阅读
  10. 求助大佬——期末考试评分标准(浙大)C语言

    2024-07-14 11:22:01       26 阅读
  11. 如何解决数据分析问题:IPython与Pandas结合

    2024-07-14 11:22:01       17 阅读
  12. 【团队成长】2024-28周周报

    2024-07-14 11:22:01       23 阅读
  13. Mysql第八次作业

    2024-07-14 11:22:01       18 阅读