顯示具有 STL 標籤的文章。 顯示所有文章
顯示具有 STL 標籤的文章。 顯示所有文章

2010年2月26日 星期五

[C++][STL] delete item in loop

STL 好用是好用,小地方還是要注意,不然很容易爆炸又難DEBUG

1. Use List:
list中erase會回傳iterator,所以要erase(it)
list<int> tmp;
for(list::iterator it = tmp.begin() ; it != tmp.end() ; /*empty*/ )
{
        if( something )
                it = tmp.erase(it);
        else
                it++;
}

2. Use Map:
map中erase竟然又不一樣,回傳void,所以需要erase(it++)
map<int,int> tmp;
for(map::iterator it = tmp.begin() ; it != tmp.end() ; /*empty*/ )
{
        if( something )
                tmp.erase(it++);
        else
                it++;
}

其實應該要看他內部為啥實做成兩種模式的
但是STL聖經一直供在桌上懶得看XD
有空再來研究

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