入門計劃->學用stl std::map (轉)

amyz發表於2007-11-25
入門計劃->學用stl std::map (轉)[@more@]

C++:一種比較流行的強大功能面向語言,應用和前景都很廣闊。

stl:C++標準模板庫,功能極其強大,將其完全掌握後C++程式設計會相當容易。

map:一種關係式容器,可以根據關鍵字匹配多種資料。

string:"to:~!@#$%">~!@#$%^&*()_+",這樣的東東就是。

以下程式碼將簡單演示如何透過名稱(string)關鍵字匹配id(int),由於程式(程式,受網上資料的影響,偶也開始想把程式說成程式,廢話)太簡單,沒有寫註釋,對於想的朋友將程式碼看明白可以自己舉一反三就算學會一招了:)高手請跳過。

程式在以下環境順利測試透過:

+VC6

7.2 + gcc(g++)2.96

--源程式--

// strmap1.cpp // #pragma warning(disable:4786) //... #include #include //... #include using namespace std; class strmap1 { typedef std::map<:string int=""> type_map; typedef type_map::iterator type_iter; type_map mm; type_iter it; int id; public: strmap1() : it(NULL), id(0) { //init id = 0; mm["i"] = ++id; mm["you"] = ++id; mm["he"] = ++id; } int find(const char* s) { cout << "find " << s << endl; int ret = 0; it = mm.find(s); if (mm.end() != it) { ret = it->second; cout << s << "'s id is " << ret << endl; } else { cout << "can't find " << s << "'s id" << endl; } return ret; } int insert(const char* s) { cout << "insert " << s << endl; int ret = ++id; mm.insert(type_map::value_type(s, ret)); //mm[s] = ret;//ok return ret; } void remove(const char* s) { cout << "remove " << s << endl; mm.erase(s); } }; int main(int argc, char* argv[]) { cout << "(strmap1)string map 1(simple use std::map)" << endl; strmap1 o; cout << endl; o.find("i"); cout << endl; o.find("she"); cout << endl; o.find("you"); o.find("he"); cout << endl; o.insert("she"); o.remove("you"); o.remove("he"); cout << endl; o.find("you"); o.find("he"); o.find("she"); cout << endl; cout << "haha~~~now only i and she" << endl; return 0; } --輸出結果--


(strmap1)string map 1(simple use std::map)


find i
i's id is 1


find she
can't find she's id


find you
you's id is 2
find he
he's id is 3


insert she
remove you
remove he


find you
can't find you's id
find he
can't find he's id
find she
she's id is 4


haha~~~now only i and she


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752019/viewspace-984540/,如需轉載,請註明出處,否則將追究法律責任。

相關文章