|
|
发表于 2025-3-23 15:51:06
|
显示全部楼层
在 printMap 函数的定义中,myCompare 是一个未定义的标识符,因为它没有被正确传递到函数中。
try this:- #include <iostream>
- #include <map>
- using namespace std;
- class myCompare
- {
- public:
- bool operator()(int v1, int v2) const
- {
- return v1 > v2;
- }
- };
- // 修正后的printMap函数
- void printMap(const map<int, int, myCompare>& mp)
- {
- for (map<int, int, myCompare>::const_iterator it = mp.begin(); it != mp.end(); it++)
- {
- cout << "键= " << it->first << " 值= " << it->second << endl;
- }
- cout << endl;
- cout << endl;
- }
- void test1()
- {
- map<int, int, myCompare> mp;
- mp.insert(make_pair(1, 30));
- mp.insert(make_pair(2, 20));
- mp.insert(make_pair(5, 50));
- mp.insert(make_pair(3, 40));
- mp.insert(make_pair(4, 70));
- printMap(mp); // 使用封装的函数打印map
- // 也可以直接遍历map
- for (map<int, int, myCompare>::iterator it = mp.begin(); it != mp.end(); it++)
- {
- cout << "键= " << it->first << " 值= " << it->second << endl;
- }
- cout << endl;
- }
- int main()
- {
- test1();
- system("pause");
- return 0;
- }
复制代码
|
|