標籤:++ namespace iter tor 筆記 log 輸出 返回 bool
map<key, value>是按key排好序的,key不可以重複。
1. map.lower_bound():按key尋找,如果尋找的key存在,返回該位置,如果不存在返回大於所尋找值的最小key所在位置
1 #include <iostream> 2 #include <map> 3 using namespace std; 4 5 int main () 6 { 7 std::map<char,int> mymap; 8 std::map<char,int>::iterator itlow,itup; 9 10 mymap[‘a‘]=20;11 mymap[‘b‘]=40;12 mymap[‘b‘]=50; //key值不重複,會把b的value更新為50 13 mymap[‘c‘]=80; //value的值可以重複14 mymap[‘d‘]=80;15 mymap[‘e‘]=100;16 17 for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)18 std::cout << it->first << " => " << it->second << ‘\n‘;19 cout<<endl;20 //這段程式其實並不能成功插入,因為key=b已經存在了,value也不會更新21 itlow=mymap.lower_bound (‘b‘); //如果索引值b存在,itlow指向b,否則指向比b大的最小key所在位置22 mymap.insert(itlow,std::map<char,int>::value_type(‘b‘,40)); //向itlow指向的位置插入map<‘b‘,40>23 24 for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)25 std::cout << it->first << " => " << it->second << ‘\n‘;26 cout<<endl;27 28 char c=‘a‘;29 while(1)30 { //輸入一個字元並插入31 cin>>c; 32 itlow = mymap.lower_bound(c);33 if(itlow != mymap.end())34 cout<<"insert "<<c<<" to position: "<<itlow->first<<" , "<<itlow->second<<‘\n‘;35 mymap.insert(itlow, map<char,int>::value_type(c, 160+c));36 for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)37 std::cout << it->first << " => " << it->second << ‘\n‘;38 cout<<endl;39 }42 return 0;43 }
輸出結果:
1 a => 20 2 b => 50 3 c => 80 4 d => 80 5 e => 100 6 7 a => 20 8 b => 50 9 c => 8010 d => 8011 e => 10012 13 d //並沒有成功插入,d的value還是原來的8014 insert d to position: d , 8015 a => 2016 b => 5017 c => 8018 d => 8019 e => 10020 21 z //插入位置在map.end22 a => 2023 b => 5024 c => 8025 d => 8026 e => 10027 z => 28228 29 x30 insert x to position: z , 28231 a => 2032 b => 5033 c => 8034 d => 8035 e => 10036 x => 28037 z => 282
2. map.key_comp(),只有第一個參數小於第二個才返回true。
函數傳回值是bool型,輸入是兩個key值,key_comp()(a,b),當a<b時返回1,否則返回0。
1 #include <iostream> 2 #include <map> 3 using namespace std; 4 int main () 5 { 6 std::map<char,int> mymap; 7 8 mymap[‘a‘] = 20; 9 mymap[‘c‘] = 120;10 mymap[‘x‘]=101;11 mymap[‘y‘]=203;12 mymap[‘z‘]=103;13 14 std::cout << "mymap contains:\n";15 map<char,int>::iterator it = mymap.begin();16 for( it = mymap.begin();it!=mymap.end();it++)17 cout<<it->first<<" => "<<it->second<<‘\n‘;18 cout<<endl;19 20 map<char,int>::iterator pit = mymap.begin();21 pit++;22 pit++; //pit指向第三個元素map<x,101>23 24 it = mymap.begin();25 for( it = mymap.begin();it!=mymap.end();it++)26 {27 cout<<"key comp result: "<<mymap.key_comp()(it->first, pit->first)<<endl;28 }29 cout<<endl;30 return 0;31 }
結果:
1 mymap contains: 2 a => 20 3 c => 120 4 x => 101 5 y => 203 6 z => 103 7 8 key comp result: 1 9 key comp result: 110 key comp result: 0 //此時it=pit11 key comp result: 012 key comp result: 0
c++學習筆記(八)- map