代码:
#include <string>
#include <cstring>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
map <string, int>test;
//pair可以将两个值视为一个单元,容器map就是用pair来管理其键值
//make_pair无需写出类型,就可以生成一个pair对象
test.insert(make_pair("test1",1));
test.insert(make_pair("test2", 2));
map<string, int>::iterator it;
it = test.find("test0");
cout << "test0 find:";
if (it == test.end())
cout << "test0 not found" << endl;
else
cout << it->second << endl;
cout << "test0 count:";
cout << test.count("test0") << endl;
it = test.find("test1");
cout << "test1 find:";
if (it == test.end())
cout << "test1 not found" << endl;
else
cout << it->second << endl;
cout << "test1 count:";
cout << test.count("test1") << endl;
return 0;
}
运行结果:
使用count,返回的是被查找元素的个数。如果有,返回1;否则,返回0。注意,map中不存在相同元素,所以返回值只能是1或0。
使用find,返回的是被查找元素的位置,没有则返回map.end()。