|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
下面是“黑马程序员”map教学案例,请看过代码后(特别是封装的打印函数)再看下我遇到的问题:
首先不使用封装的函数,遍历map是正常的,但是当使用封装的函数(printMap)遍历时,提示错误,在传递参数和定义迭代器it时,无论带不带myCompare,都提示错误,因为本人刚学习到map章节,理解能力有限,特向大神求助。
#include <iostream>
#include <map>
using namespace std;
//void printMap(map<int, int,myCompare>& mp)
//{
// for (map<int, int, myCompare>::iterator it = mp.begin(); it != mp.end(); it++)
// {
// cout << "键= " << it->first << " 值= " << it->second << endl;
// }
// cout << endl;
// cout << endl;
//}
class myCompare
{
public:
bool operator()(int v1,int v2)const
{
return v1 > v2;
}
};
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);
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;
}
在 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;
- }
复制代码
|
|