std 學習 std::map用法學習

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.