C++ STL中在map或multimap中查找元素
诸如 map 和 multimap 等关联容器都提供了成员函数 find(),它让您能够根据给定的键查找值。
find( )总是返回一个迭代器:
multimap <int, string>::const_iterator pairFound = mapIntToStr.find(key);
您应首先检查该迭代器,确保 find( )已成功,再使用它来访问找到的值:
if (pairFound != mapIntToStr.end())
{
cout << "Key " << pairFound->first << " points to Value: ";
cout << pairFound->second << endl;
}
else
cout << “Sorry, pair with key " << key << " not in map” << endl;
如果您使用的编译器遵循 C++11 标准,可使用关键字 auto 来简化迭代器声明:
auto pairFound = mapIntToStr.find(key);
编译器将根据 map::find( )的返回类型自动推断出迭代器的类型。
程序清单 20.3 演示了 multimap::find()的用法
0: #include <map>
1: #include <iostream>
2: #include <string>
3: using namespace std;
4:
5: