⚠️ 把"怎么比"当参数传进去

👁️ 2 人浏览 💬 0 人评论 ❤️ 添加收藏

(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)容器把它写进模板参数,算法把它写进函数参数:

#include <iostream>
#include <functional>
#include <map>
#include <string>
#include <vector>
#include <algorithm>

int main() {
    /* 容器的模板参数里,除了元素类型还能塞"怎么比" */
    std::map<std::string, int> asc{{"b", 2}, {"a", 1}, {"c", 3}};
    std::map<std::string, int, std::greater<std::string>> desc{
        {"b", 2}, {"a", 1}, {"c", 3}};

    /* 算法那边,"怎么比"是当参数传进去的 */
    std::vector<int> v{5, 3, 9};
    std::sort(v.begin(), v.end(), std::greater<int>());

    std::cout << asc.begin()->first << "/" << desc.begin()->first << "/"
              << v.front() << "\n";
    return 0;
}
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论