map映射
map實(shí)例代碼:
1 // UVa156 Ananagrams 2 // Rujia Liu 3 // 題意:輸入一些單詞,找出所有滿足如下條件的單詞:該單詞不能通過字母重排得到輸入文本中的另外一個(gè)單詞 4 // 算法:把每個(gè)單詞“標(biāo)準(zhǔn)化”,即全部轉(zhuǎn)化為小寫字母然后排序,然后放到map中進(jìn)行統(tǒng)計(jì) 5 #include<iostream> 6 #include<string> 7 #include<cctype> 8 #include<vector> 9 #include<map> 10 #include<algorithm> 11 using namespace std; 12 13 map<string,int> cnt; 14 vector<string> words; 15 16 // 將單詞s進(jìn)行“標(biāo)準(zhǔn)化” 17 string repr(string s) { 18 string ans = s; 19 for(int i = 0; i < ans.length(); i++) 20 ans[i] = tolower(ans[i]); 21 sort(ans.begin(), ans.end()); 22 return ans; 23 } 24 25 int main() { 26 int n = 0; 27 string s; 28 while(cin >> s) { 29 if(s[0] == '#') break; 30 words.push_back(s); 31 string r = repr(s); 32 if(!cnt.count(r)) cnt[r] = 0; 33 cnt[r]++; 34 } 35 vector<string> ans; 36 for(int i = 0; i < words.size(); i++) 37 if(cnt[repr(words[i])] == 1) ans.push_back(words[i]); 38 sort(ans.begin(), ans.end()); 39 for(int i = 0; i < ans.size(); i++) 40 cout << ans[i] << "\n"; 41 return 0; 42 } View Code?
map添加數(shù)據(jù):
1 map<int ,string> maplive; 2 maplive.insert(pair<int,string>(102,"aclive"));//法1 3 maplive.insert(map<int,string>::value_type(321,"hai"));//法2 4 maplive[112]="April";//map中最簡單最常用的插入添加!map中元素的查找:
?find()函數(shù)返回一個(gè)迭代器指向鍵值為key的元素,如果沒找到就返回指向map尾部的迭代器。?
1 map<int ,string >::iterator l_it;; 2 l_it=maplive.find(112); 3 if(l_it==maplive.end()) 4 cout<<"we do not find 112"<<endl; 5 else cout<<"wo find 112"<<endl;map中元素的刪除:
1 map<int ,string >::iterator l_it;; 2 l_it=maplive.find(112); 3 if(l_it==maplive.end()) 4 cout<<"we do not find 112"<<endl; 5 else maplive.erase(l_it); //delete 112;map的sort問題:
??Map中的元素是自動(dòng)按key升序排序,所以不能對(duì)map用sort函數(shù)
轉(zhuǎn)載于:https://www.cnblogs.com/cyb123456/p/5798787.html
總結(jié)
- 上一篇: 8-1:C++继承之对继承的理解和继承的
- 下一篇: (王道408考研操作系统)第二章进程管理