如果您有权访问优秀的boost库,那么您应该使用boost::multi_index来创建bidirectional map,正如Mark所说的那样。与std :: map不同,这允许您通过键或值来查找。
如果你只有STL手下面的代码就可以了(模板与任何类型的地图,其中mapped_type支持==操作符的工作):
#include <map>
#include <string>
#include <algorithm>
#include <iostream>
#include <cassert>
template<class T>
struct map_data_compare : public std::binary_function<typename T::value_type,
typename T::mapped_type,
bool>
{
public:
bool operator() (typename T::value_type &pair,
typename T::mapped_type i) const
{
return pair.second == i;
}
};
int main()
{
typedef std::map<std::string, int> mapType;
mapType map;
map["a"] = 1;
map["b"] = 2;
map["c"] = 3;
map["d"] = 4;
map["e"] = 5;
const int value = 3;
std::map<std::string, int>::iterator it = std::find_if(map.begin(), map.end(), std::bind2nd(map_data_compare<mapType>(), value));
if (it != map.end())
{
assert(value == it->second);
std::cout << "Found index:" << it->first << " for value:" << it->second << std::endl;
}
else
{
std::cout << "Did not find index for value:" << value << std::endl;
}
}
你打败了我:)好的答案。 – 2009-02-11 03:47:40