链接:https://vjudge.net/problem/UVA-156
map就是从key到value的映射。因为重载了[]运算符,map像是数组的“高级版”。例如可以用一个map<string,int> month_name来表示“月份名字到月份编号”的映射,然后用month_name["July"]=7这样的方式来赋值。
题意:输入单词,单词不能通过重新排列得到另外一个给出的单词,把满足条件的单词以保留大小写的形式用字典序排列输出。
分析:把每个单词“标准化”,即转为小写字母重新排序,然后放入map统计。如果一个字符串只对应数字为1就满足条件。
此例说明,如果没有良好的代码设计,是无法发挥STL的威力的。如果没有想到“标准化”这个思路,就很难用map简化代码。
set头文件中的set和map头文件中的map分别是集合与映射。二者都支持insert、find、count和remove操作,并且可以按照从小到大的顺序循环遍历其中的元素。map还提供了“[]”运算符,是的map可以像数组一样使用。事实上,map也称为“关联数组”。
#include <iostream> #include <string> #include <cctype> #include <vector> #include <map> #include <algorithm> using namespace std; map<string,int> cnt; vector<string> words; //将单词s进行“标准化” string repr(const string& s) { string ans=s; for(int i=0;i<ans.size();i++) ans[i]=tolower(ans[i]); sort(ans.begin(),ans.end()); return ans; } int main() { string s; while(cin>>s) { if(s[0]=='#')//结束输入 break; words.push_back(s);//放入数组 string r=repr(s);//标准化s if(!cnt.count(r))//count 查找r的个数如果有 返回1 否则 返回0 map 中不存在相同元素 只能是1或是0 cnt[r]=0;//对没有 r 的键值赋0 cnt[r]++; } vector<string> ans; for(int i=0;i<words.size();i++) if(cnt[repr(words[i])]==1)//标准话后看有无重复 ans.push_back(words[i]); sort(ans.begin(),ans.end());//字典序排列 for(int i=0;i<ans.size();i++) cout<<ans[i]<<"\n"; return 0; }
#include <iostream> #include <map> using namespace std; int main() { map<string,int> test; test.insert(make_pair("test1",1)); test.insert(make_pair("test2",2)); map<string,int>::iterator it; it=test.find("test0"); cout<<"test0 find:"; if(it==test.end()) cout<<"test0 not found\n"; else cout<<it->second<<endl; cout<<"test0 count:"; cout<<test.count("test0")<<"\n"; cout<<"test1 find:"; it=test.find("test1"); if(it==test.end()) cout<<"test1 not found.\n"; else cout<<it->second<<"\n"; cout<<"test1 count:"; cout<<test.count("test1")<<"\n"; cout<<"after inserting test1\n"; test.insert(make_pair("test1",2)); cout<<"test1 find:"; it=test.find("test1"); if(it==test.end()) cout<<"test1 not found\n"; else cout<<it->second<<"\n"; cout<<"test1 count:"<<test.count("test1")<<"\n"; return 0; }