C++:一種比較流行的強大功能物件導向程式設計語言,應用和前景都很廣闊。
stl:C++標準模板庫,功能極其強大,將其完全掌握後C++編程會相當容易。
map:一種關係式容器,可以根據關鍵字匹配多種資料。
string:"~!#$%^&*()_+",這樣的東東就是。
以下程式碼將簡單示範如何通過名稱(string)關鍵字匹配id(int),由於程式簡單,沒有寫注釋,對於想入門的朋友將代碼看明白可以自己舉一反三就算學會一招了:)高手請跳過。
程式在以下環境順利測試通過:
WIN2K+VC6
RedHat Linux 7.2 + gcc(g++)2.96
--來源程式--
// strmap1.cpp//#pragma warning(disable:4786)//...#include <map> #include <string> //...#include <iostream>using namespace std;class strmap1{ typedef std::map<std::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<string, int>)" << 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<string, int>)
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