STL之映射map&multimap

轉自http://www.cnblogs.com/tla001/ 一起學習,一起進步

map

1.insert

第一種:用insert函數插入pair數據

#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
       map<int, string> map;
       map.insert(pair<int, string>(1, “one”));
       map.insert(pair<int, string>(2, “two”));
       map.insert(pair<int, string>(3, “three”));
       map<int, string>::iterator  iter;
       for(iter = map.begin(); iter != map.end(); iter++)
        {
          cout<<iter->first<<”   ”<<iter->second<<end;
        }
}
第二種:用insert函數插入value_type數據
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
       map<int, string> map;
       map.insert(map<int, string>::value_type (1, “one”));
       map.insert(map<int, string>::value_type (2, “two”));
       map.insert(map<int, string>::value_type (3, “three”));
       map<int, string>::iterator  iter;
       for(iter = map.begin(); iter != map.end(); iter++)
        {
          cout<<iter->first<<”   ”<<iter->second<<end;
        }
}
第三種:用數組方式插入數據
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
       map<int, string> map;
       map[1]=“one”;
       map[2]=“two”;
       map[3]= “three”;
       map<int, string>::iterator  iter;
       for(iter = map.begin(); iter != map.end(); iter++)
        {
          cout<<iter->first<<”   ”<<iter->second<<end;
        }
}
map 總是以(key,value)的形式存在,當插入的數據的key已經存在時,會形成覆蓋,map內部使用紅黑樹實現。

 2.size

返回map的大小
 
3.遍歷
  可以使用迭代器方式,如1中的例子
  也可以使用[],但是注意索引從1開始
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
       map<int, string> map;
       map.insert(pair<int, string>(1, “one”));
       map.insert(pair<int, string>(2, “two”));
       map.insert(pair<int, string>(3, “three”));
       for(int index=1;index<=map.size();index++)
        {
          cout<<map[index]<<endl;
        }
}

4.查找

map.find()如果查找到,返回指向結果的迭代器,如果沒有找到到,返回map.end()。

5.上下界

lower_bound函數用法,這個函數用來返回要查找關鍵字的下界(是一個迭代器),返回鍵值>=給定元素的第一個位置。
upper_bound函數用法,這個函數用來返回要查找關鍵字的上界(是一個迭代器),返回鍵值>給定元素的第一個位置 。

6.清空與判空

清空map中的數據可以用clear()函數,判定map中是否有數據可以用empty()函數,它返回true則說明是空map。
multimap和map的區別在於,multimap允許key重複,其他沒啥特別的地方,底層也是紅黑樹實現。
 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章