std:地图由value反求key的模板函数
std::map由value反求key的模板函数
在我锲而不舍的努力下,std::map由value反求key的模板函数终于出炉了:使用时一定要把map的具现类型也传进去,想琢磨去掉这个模板参数的同学不信就试试,一定会死的很难看的。
#include <algorithm>
template <class K, class V>
class value_equals//本模板类来自于<The C++ Standard Library>
{
private:
V value;
public:
// constructor (initialize value to compare with)
value_equals (const V& v) : value(v) {}
// comparison
bool operator() (pair<const K, V> elem)
{
return elem.second == value;
}
};
template <typename K,typename V,typename Map>
K FindKeyByValue(const Map& m, const V& v)//本模板函数由johnsmith9th原创,引用请注明来自于http://johnsmith9th.iteye.com
{
typename Map::const_iterator pos = find_if(m.begin(),m.end(), value_equals<K,V>(v));
if (pos != m.end())
{
return pos->first;
}
K defaultKeyValue;
return defaultKeyValue;
}
在我锲而不舍的努力下,std::map由value反求key的模板函数终于出炉了:使用时一定要把map的具现类型也传进去,想琢磨去掉这个模板参数的同学不信就试试,一定会死的很难看的。
#include <algorithm>
template <class K, class V>
class value_equals//本模板类来自于<The C++ Standard Library>
{
private:
V value;
public:
// constructor (initialize value to compare with)
value_equals (const V& v) : value(v) {}
// comparison
bool operator() (pair<const K, V> elem)
{
return elem.second == value;
}
};
template <typename K,typename V,typename Map>
K FindKeyByValue(const Map& m, const V& v)//本模板函数由johnsmith9th原创,引用请注明来自于http://johnsmith9th.iteye.com
{
typename Map::const_iterator pos = find_if(m.begin(),m.end(), value_equals<K,V>(v));
if (pos != m.end())
{
return pos->first;
}
K defaultKeyValue;
return defaultKeyValue;
}