c++ STL 映射:map

 

Map是STL的一个关联容器,它提供一对一(其中第一个能够称为关键字,每一个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据 处理能力,因为这个特性, 它完成有可能在咱们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一 种非严格意义上的平衡二叉树),这颗树具备对数据自动排序的功能,因此在map内部全部的数据都是有序的。

功能:创建key-value的映射  key与value是任何你须要的类型  exp:map<char,int> a   创建一个char到int的映射a。ios

经常使用语句:begin()返回map头部迭代器编程

              end()返回尾部迭代器ide

             clear()清空全部元素函数

             erase()删除一个元素spa

             find()查找一个元素code

             empty()若是为空则返回true排序

             size()返回map大小ci

             count(elem)返回某个元素个数字符串

例题:UVa 156 -反片语input

大意是给你几串字符串 求出自身字符随意组合后不会出如今这些字符串里面的字符串 按字典序排序。

Sample input

 

ladder came tape soon leader acme RIDE lone Dreis peat
 ScAlE orb  eye  Rides dealer  NotE derail LaCeS  drIed
noel dire Disk mace Rob dries
#

 

Sample output

 

Disk
NotE
derail
drIed
eye
ladder
soon

分析


这道题的解法不少,最简化的方式就是使用map容器。想到使用“标准化”。
总体思路:
1.写一个标准化函数(实现大写字母转换为小写(tolower()函数),单词排序。注意使用const是为了避免改变s的初值)
2.两个vector容器(words,ans),一个map容器(cnt)
words存储全部的单词
map存储标准化后对应单词以及出现次数的值,至关于一个表格。
words通过查表map,把对应的符合值给ans
感受初次写map仍是挺爽的...

#include<iostream>#include<map>#include<vector>#include<string>#include<algorithm>using namespace std;map<string,int>mmap;vector<string> str;string standard(const string &s){ string t=s; for(int i=0;i<s.size();i++) { t[i]=tolower(s[i]);//转换成小写字母  } sort(t.begin(),t.end()); return t;}int main(){ string s; while(cin>>s) { if(s[0]=='#') break; str.push_back(s);//推入vector  string r=standard(s);//将其标准化 mmap[r]++; } vector<string>ans; for(vector<string>::iterator it=str.begin();it!=str.end();it++) { if(mmap[standard(*it)]==1) ans.push_back(*it); } sort(ans.begin(),ans.end()); for(vector<string>::iterator it=ans.begin();it!=ans.end();it++) {     cout<<*it<<endl; } return 0; } 

相关文章
相关标签/搜索