⚠️ 把"怎么比"当参数传进去
(本条路线统一用 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;
}
全部评论