第21章STL map 和 multimap

1.map和multimap是鍵-值對容器。可以根據鍵查找。map只能是唯一的鍵,multimap可以存在重複的鍵

2.map和multimap內部結構和二叉樹差不多。插入元素的時候要進行排序。這樣查找起來更加迅速。不過不可以像vector那樣找到一個元素的位置,進行替換,因爲數據是需要排序的。

3.模版需要包含<map>頭文件

4.創建

map<int, string> a;

multimap<int, string> b;

第一個是key,第二個是value,還有一個參數可選謂詞,用來排序。指明就用默認的

5.插入元素 

#include <map>
#include <isotream>
using namespace std;
int main(){
map<int, string> a;
a.insert(map<int, string>::value_type(3, "three"));
a.insert(make_pair(-1, "minus one"));
a.insert(pair<int, string>(1000, "one thousand"));
a[10] = "ten";
map<int, string>::const_iterator i;
for(i = a.begin(); i!=a.end(); ++i){
cout <<"key: "<<i->first;
cout<< " value: "<<i->second.c_str();
cout << endl;
}

multimap<int, string> a;
b.insert(multimap<int, string>::value_type(3,"three"));
b.insert(multimap<int, string>::value_type(45, "forty five"));
b.insert(make_pair(-1, "minus one"));
b.insert(pair<int, string>(1000, "one thousand"));
b.insert(multimap<int, string>::value_type(1000,"thousand"));
multimap<int, string>::const_iterator j;
for(j=b.begin(); j!=b.end(); ++j){
cout<<j->first<<j->second.c_str();
}
cout<<"the number of pairs in the multimap with 1000 as their key: " << b.count(1000)<<endl;
return 0;
}

6.刪除元素

multimap<int, string> a;

a.insert...

a.erase(2);//刪除a中所有key爲2的元素

multimap<int, string>::iterator i;

i=a.find(34);

a.erase(i);//找到a中的34,然後刪除

a.erase(a.lower_bound(2), a.upper_bound(0));//刪除a中大於0小於2的元素

在刪除的時候傳遞給erase的迭代器不要const_iterator,因爲我們需要改變,所以用iterator

 7.提供自定義排序謂詞

#include<map>

#include<algorithm>

#include<string>

#include<iostream>

using namespace std;

struct cc{

bool operator()(const string & str1, const string & str2)const{

string str1no(str1), str2no(str2);

transform(str1.begin(), str1.end(), str1no.begin(), tolower);

transform(str2.begin(), str2.end(), str2no.begin(), tolower);

return (str1no<str2no);

};

};

int main(){

map<string, string, cc> a;

a.insert(map<string, string, cc>::value_type("john", "23423"));

a.insert(map<string, string, cc>::value_type("JOHN", "23423"));

a.insert(map<string, string, cc>::value_type("sara", "234"));

a.insert(map<string, string, cc>::value_type("jack", "45345"));

map<string, string, cc>::const_iterator i;

for(i=a.begin(); i!=a.end(); i++){

cout<<i->first<<i->second;

}

map<string, string, cc>::iterator i = a.find("JOhn");

return 0;

}


調用find函數時,由於我們定義了一個謂詞,來實現()方法,所以不區分大小寫,能夠找到

8.map<int, less<int>>這是降序,默認的

map<int, greater<int>>這是升序

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