2010年2月3日 星期三

[C++][STL] map如何使用一個struct當作key

拿來當key的struct,裡面有兩個variables:
struct S
{
        int x;
        int y;
};
由於map在insert時就會用KEY做排序,所以必須自己寫一個比較函式:
struct CmpFunction
{
        bool operator() ( const struct S s1, const struct S s2 ) const
        {
                return ( (s1.x < s2.x) || ((s1.x == s2.x) && (s1.y < s2.y)) );
        }
};
接下來就可以直接定義map的typedef,比較簡單好用:
typedef std::map<struct S, int value , CmpFunction> map_t;
宣告:
map_t mymap;
如此一來就可以用find去快速搜尋:
struct S mystruct;
map_t::iterator iter = mymap.find( mystruct );
if( iter == mymap.end() ) // not found
else // found

沒有留言: