map实例代码:
1 // UVa156 Ananagrams 2 // Rujia Liu 3 // 题意:输入一些单词,找出所有满足如下条件的单词:该单词不能通过字母重排得到输入文本中的另外一个单词 4 // 算法:把每个单词“标准化”,即全部转化为小写字母然后排序,然后放到map中进行统计 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进行“标准化” 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 }
map添加数据:
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()函数返回一个迭代器指向键值为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中的元素是自动按key升序排序,所以不能对map用sort函数
1 #include <map> 2 #include <iostream> 3 using namespace std; 4 int main( ) 5 { 6 map <int, int> m1; 7 map <int, int>::iterator m1_Iter; 8 m1.insert ( pair <int, int> ( 1, 20 ) ); 9 m1.insert ( pair <int, int> ( 4, 40 ) ); 10 m1.insert ( pair <int, int> ( 3, 60 ) ); 11 m1.insert ( pair <int, int> ( 2, 50 ) ); 12 m1.insert ( pair <int, int> ( 6, 40 ) ); 13 m1.insert ( pair <int, int> ( 7, 30 ) ); 14 cout << "The original map m1 is:"<<endl; 15 for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ ) 16 cout << m1_Iter->first<<" "<<m1_Iter->second<<endl; 17 18 } 19 /* 结果是 20 The original map m1 is: 21 1 20 22 2 50 23 3 60 24 4 40 25 6 40 26 7 30 27 */ 28 请按任意键继续. . .
时间: 2024-11-05 18:38:47