STL之map

下面的代碼實現map的刪除,添加,清空的基本操作; 對於map的find方法很多新手比較困惑,若果找不到迭代器返回值是什麼?

答案是會返回end()。


    #include <map>  
    #include <string>  
    #include <iostream>  
    using namespace std;  
    int _tmain(int argc, _TCHAR* argv[])  
    {   
      
      
            map<int, string> mapStudent;  
      
            mapStudent.insert(pair<int, string>(10001,"bojie")); //添加  
      
            mapStudent.insert(pair<int, string>(10002,"小明"));  
      
            mapStudent.insert(pair<int, string>(10004,"小雪"));  
      
            mapStudent.insert(pair<int, string>(10005,"小小"));  
      
                    mapStudent.insert(pair<int, string>(10003,"小白"));//map默認會自動按第一個key從小到大排序。  
      
            map<int, string>::iterator  iter;  
      
            for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
      
            {  
                cout<<iter->first<<"  "<<iter->second<<endl;  
                  
            }  
                    cout<<endl;  
      
            mapStudent.erase(10001); //刪除<p>            //  其中如果要刪除還有一種常用的方法,用迭代器刪除 ,如下</p><p>            //   map<int, string>::iterator iter;</p><p>            //   iter = mapStudent.find(1);</p><p>            //    mapStudent.erase(iter);  
            for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
            {  
                cout<<iter->first<<"  "<<iter->second<<endl;  
            }  
      
            mapStudent.clear();    //清空  
            for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
            {  
                cout<<iter->first<<"  "<<iter->second<<endl;  
            }  
      
               while(1);  
           return 0;  
    }  

map的基本操作函數:
      C++ Maps是一種關聯式容器,包含“關鍵字/值”對
      begin()          返回指向map頭部的迭代器
      clear()         刪除所有元素
      count()          返回指定元素出現的次數
      empty()          如果map爲空則返回true
      end()            返回指向map末尾的迭代器
      equal_range()    返回特殊條目的迭代器對
      erase()          刪除一個元素
      find()           查找一個元素
      get_allocator()  返回map的配置器
      insert()         插入元素
      key_comp()       返回比較元素key的函數
      lower_bound()    返回鍵值>=給定元素的第一個位置
      max_size()       返回可以容納的最大元素個數
      rbegin()         返回一個指向map尾部的逆向迭代器
      rend()           返回一個指向map頭部的逆向迭代器
      size()           返回map中元素的個數
      swap()            交換兩個map
      upper_bound()     返回鍵值>給定元素的第一個位置
      value_comp()      返回比較元素value的函數

發佈了27 篇原創文章 · 獲贊 12 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章