以前看到有人出了一道单词统计题,意思大概是, 有一个words.txt文件的内容如下:
some
are
born
great
some
achieve
greatness
and
some
have
greatness
thrust
upon
them
用程序读取该文件,统计相同的单词数,并按字符顺序写入另一个文件,如result.txt
achieve 1
and 1
are 1
born 1
great 1
greatness 2
have 1
some 3
them 1
thrust 1
upon 1
现用两种STL方法(即vector和map)解如下:
/vector//
- #include <fstream>
- #include <iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
- using namespace std;
- struct Count
- {
- string name;
- double val;
- Count(string n="",double v=0):name(n),val(v){}
- };
- bool sort_name(const Count & m1, const Count & m2)
- {
- return strcmp(m1.name.c_str(),m2.name.c_str())<=0 ? true:false;
- }
- vector<Count> counts;
- double& value(const string& s)
- {
- for (int i=0;i<counts.size();i++)
- {
- if (s==counts[i].name)
- return counts[i].val;
- }
- counts.push_back(Count(s));
- return counts[counts.size()-1].val;
- }
- int main()
- {
- ifstream ifs("words.txt");
- string buf;
- while(ifs)
- {
- if(getline(ifs,buf))
- value(buf)++;
- }
- ifs.close();
- sort(counts.begin(), counts.end(),sort_name);
- ofstream ofs("result.txt");
- for(vector<Count>::const_iterator p=counts.begin();p!=counts.end();++p)
- {
- cout<<p->name<<'/t'<<p->val<<'/n';
- ofs<<p->name<<'/t'<<p->val<<'/n';
- }
- ofs.close();
- return 0;
- }
//map/
- #include <fstream>
- #include <iostream>
- #include <string>
- #include <map>
- #include <algorithm>
- using namespace std;
- typedef map<string,int>::const_iterator CI;
- void Insert(map<string,int>& m)
- {
- string word;
- int val=1;
- ifstream ifs("words.txt");
- while (ifs)
- {
- if(getline(ifs,word))
- m[word]+=val;
- }
- ifs.close();
- }
- int main()
- {
- map<string,int> tbl;
- Insert(tbl);
- ofstream ofs("result.txt");
- for (CI p=tbl.begin();p!=tbl.end();++p)
- {
- cout<<p->first<<'/t'<<p->second<<'/n';
- ofs<<p->first<<'/t'<<p->second<<'/n';
- }
- ofs.close();
- return 0;
- }