bloggerads

2013年11月2日 星期六

C++的Container: Map使用範例

C++提供map容器, [key]=value. 使用key來找尋找、插入、刪除.

map容器的排列會根據key來自動排列. (是一種平衡二元素的實現)


以下是範例:


#include <iostream>
#include <string>
#include <map>
using namespace std;
int find_and_erase(map<string, string> &mm, string ss)
{
    map<string, string>::iterator it;
    //find and erase the element
    if ( mm.end() != ( it = mm.find(ss)) ) {
        mm.erase(it); cout << ">Erase " << ss << endl;
    }else  cout << ">Cannot find " << ss << endl;
}
int show_all(string ss, map<string, string> mm)
{
    map<string, string>::iterator it;
    for(it = mm.begin(); it != mm.end(); it++)
                cout<<it->first<<" "<<it->second<<endl;
    cout << "****Finish job: "<< ss << endl;    
}

int main()
{  
    map<string, string> mm;
 
    mm["John"] = "John_data";
    mm["May"]  = "May_data";
    show_all("add John & May", mm);
    if ( false == mm.insert(pair<string, string>("Martin", "Martin_data")).second )
        cout << "(insert failed)" << endl;
    show_all("insert Martin", mm);
    // Insert same key twice, should get failed return
    if ( false == mm.insert(pair<string, string>("Martin", "Martin_data")).second )
        cout << "(insert failed)" << endl;
    show_all("insert Martin", mm);    
   
    cout << "total size: " << mm.size() << endl;
   
    find_and_erase(mm, "John");
    show_all("erase John", mm);
       
    // Reverse iterator
    for (map<string, string>::reverse_iterator itr = mm.rbegin(); itr != mm.rend(); itr++)
        cout<<itr->first<<" "<<itr->second<<endl;
    cout << "****Reverse Traversal" << endl;
    return 0;
}

Output:

John John_data
May May_data
****Finish job: add John & May
John John_data
Martin Martin_data
May May_data
****Finish job: insert Martin
(insert failed)
John John_data
Martin Martin_data
May May_data
****Finish job: insert Martin
total size: 3
>Erase John
Martin Martin_data
May May_data
****Finish job: erase John
May May_data
Martin Martin_data
****Reverse Traversal

沒有留言:

張貼留言