#include <iostream> #include <string> #include <map> using namespace std; //自己手写的仿函数 class MyCompare { public: bool operator()(string s1, string s2) const // 注意此处一定要加上 const 在VS2022中,否则会报错 : 有类型“const MyCompare”的表达式会丢失一些 const - volatile 限定符以调用“bool MyCompare::operator ()(std::string, std: { return s1 > s2; } }; void printMap(map<string, int, MyCompare>& m) { for (map<string, int> ::iterator it = m.begin(); it != m.end(); it++) { cout << "Key= " << it->first << " ,Value= " << it->second << endl; } } void test01() { // map容器的构造 map<string, int, MyCompare> m; // map容器默认排序 m.insert(make_pair("Tom", 18)); m.insert(make_pair("Anthony", 23)); m.insert(make_pair("Bob", 24)); m.insert(make_pair("Sunny", 19)); printMap(m); } int main() { test01(); system("pause"); return 0; }
用标准库定义的仿函数:
// Study01.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include <string> #include <map> #include <functional> using namespace std; void printMap(map<string, int, greater<string>>& m) { for (map<string, int, greater<string>> ::iterator it = m.begin(); it != m.end(); it++) { cout << "Key= " << it->first << " ,Value= " << it->second << endl; } } void test01() { // map容器的构造 map<string, int, greater<string>> m; // map容器默认排序 m.insert(make_pair("Tom", 18)); m.insert(make_pair("Anthony", 23)); m.insert(make_pair("Bob", 24)); m.insert(make_pair("Sunny", 19)); printMap(m); } int main() { test01(); system("pause"); return 0; }