假設map為假設map為<string, int>,首先先定義比較的方法:,首先先定義比較的方法:
class Value2Key_
{
public:
Value2Key_(const int& second) : m_second(second) {}
bool operator() (const std::map<string ,int>::value_type& v)
{
return v.second == m_second ? true : false;
}
private:
const int& m_second;
};
然後再定義如何取得:
string Value2Key(const std::map<string , int>& refmap ,int second)
{
std::map<string,int>::const_iterator it = std::find_if(refmap.begin(), refmap.end(), Value2Key_(second));
return it != refmap.end() ? it->first : string();
}不過嘛,其實直接寫個for來訪查就可以了,若是程式中大量用到同種類型的map,且常常需要用到map來取得資料的話,這倒是可以考慮用看看,不然每次都寫個for也是很浪費時間的事。
0 意見:
張貼留言