根据《C++标准程序库》中描述,对于map的find()成员函数,可以用来搜寻拥有某个key的第一个元素,但是不能搜寻持有某特定value的元素。
如果搜寻某特定value,需要使用find_if(),或者循环遍历。
以下示例如何使用find_if():
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
typedef std::map<std::string, int> map_type;
template <class K, class V>
class map_find_func{
private:
V value;
public:
map_find_func(const V& v) :
value(v) {
}
bool operator()(std::pair<const K, V>& elem) {
return (elem.second == value);
}
};
int main()
{
map_type col1;
col1.insert(std::make_pair("1234", 1));
col1.insert(std::make_pair("2234", 2));
map_type::iterator it = std::find_if(col1.begin(), col1.end(),
map_find_func<std::string, int>(1));
if (it != col1.end())
{
std::cout << it->first << std::endl;
}
}
输出结果:
1234
Press any key to continue