STL Map的搜尋

制定了一個std::map後,如果要搜尋first所代表的值的話,除了直接用map[要搜尋的東西]或是map.find就可以得到,但是second的呢?當然,直接訪查map的所有成員並做比對就可以,這邊提供一個利用STL來訪查的方法。

假設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 意見:

張貼留言