STL詳解map和multimap

map:自動排序,間不可以重複

multimap:自動排序,間可以重複

鍵值對:鍵就是姓名,值就是後面的信息,比如性別,班級,年齡

#include <iostream>
using namespace std;
#include <map>
void f1() {
map<int, string> mymap;
mymap.insert(pair<int, string> (4, "four"));
mymap.insert(pair<int, string> (2, "two"));
mymap.insert(pair<int, string> (3, "three"));
mymap.insert(pair<int, string> (2, "threexx"));


map<int, string>::iterator it;
for (it = mymap.begin(); it != mymap.end(); it++) {
//不能改鍵名
// it->first=3;
//能改值
if (it->first == 3)
it->second = "xx";
cout << it->first << ":" << it->second << endl;
}
}


void f2() {
multimap<int, string> mymap;
mymap.insert(multimap<int, string>::value_type(3, "three"));
mymap.insert(multimap<int, string>::value_type(1, "one"));
mymap.insert(multimap<int, string>::value_type(2, "two"));
mymap.insert(multimap<int, string>::value_type(1, "xcfsdfsd"));
multimap<int, string>::iterator it;
for (it = mymap.begin(); it != mymap.end(); it++) {
cout << it->first << ":" << it->second << endl;
}
}
void f3() {
map<int, string> mymap;
mymap[1] = "one";
mymap[3] = "three";
mymap[3] = "threexx";
mymap[2] = "two";


map<int, string>::iterator it;
for (it = mymap.begin(); it != mymap.end(); it++) {
cout << it->first << ":" << it->second << endl;
}
}


//void f5() {
// multimap<int, string> mymap;
// mymap.insert(pair<int, string> (1, "one"));
// mymap.insert(pair<int, string> (3, "three"));
// mymap.insert(pair<int, string> (1, "two"));
// map<int, string>::iterator it;
// for (it = mymap.begin(); it != mymap.end(); it++) {
// cout << it->first << ":" << it->second << endl;
// }
//}
int main() {
f2();
return 0;
}

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