样例输出
THIS:****4 IS:****4 A:**2 TEST:****4 EASY:**2 本来想用map做,可发现输出顺序为单词输入顺序,所以决定用vector容器,元素类型是pair<string,int> 我还用到了输入控制,cin.get(),具体用法及示例见我的博客:http://blog.csdn.net/reidsc/article/details/69053919 transform用法(转) transform函数的作用是:将某操作应用于指定范围的每个元素。transform函数有两个重载版本: transform(first,last,result,op);//first是容器的首迭代器,last为容器的末迭代器,result为存放结果的容器,op为要进行操作的一元函数对象或sturct、class。 例如将string大小写反转就可以用transform来实现 #include <iostream> #include <algorithm> using namespace std; char op(char ch) { return isupper(ch)?(ch-'A'+'a'):(ch-'a'+'A'); } int main() { string str,rstr; cin>>str; rstr.resize(str.length()); transform(str.begin(),str.end(),rstr.begin(),op); cout<<rstr<<endl; return 0; } 输入:ABCdef 输出:abcDEF transform(first1,last1,first2,result,binary_op);//first1是第一个容器的首迭代器,last1为第一个容器的末迭代器,first2为第二个容器的首迭代器,result为存放结果的容器,binary_op为要进行操作的二元函数对象或sturct、class。 例如:求两多项式的和 #include <iostream> #include <algorithm> #include <vector> using namespace std; void print(int &elem) { cout<<elem<<" "; } int op(int a,int b) { return a+b; } int main() { vector <int> A,B,SUM; int n,t; cin>>n; for(int i=0;i<n;i++) { cin>>t; A.push_back(t); } for(int i=0;i<n;i++) { cin>>t; B.push_back(t); } SUM.resize(n); transform(A.begin(),A.end(),B.begin(),SUM.begin(),op); for_each(SUM.begin(),SUM.end(),print); return 0; } 输入: 5 1 2 3 4 5 -1 3 6 7 0 输出: 0 5 9 11 5 注意:第二个重载版本必须要保证两个容器的元素个数相等才行,否则会抛出异常。 题目代码: #include<iostream> #include<vector> #include<algorithm> #include<string> using namespace std; vector<pair<string,int> > word; int main() { string s; int i; while(cin>>s)//单个按词输入 { if(s[s.length()-1]=='.'||s[s.length()-1]==',')//如果是句号或者逗号就去掉 s.erase(--s.end()); transform(s.begin(),s.end(),s.begin(),::toupper);//toupper是将将字符转化为大写的函数 for(i=0;i<word.size();i++) if(word[i].first==s) break; if(i==word.size())//如果未找到这个单词就就将单词存进去 word.push_back(make_pair(s,1)); else//如果找到了就把它的频数+1 word[i].second++; if(cin.get()==10) break; } for(i=0;i!=word.size();i++) { cout<<word[i].first<<":"; for(int j=0;j<word[i].second;j++) cout<<"*"; cout<<word[i].second<<endl; } return 0; }