【发布时间】:2011-05-23 22:52:39
【问题描述】:
您好,我正在编写一个程序来计算每个单词在文件中出现的次数。然后它会打印一个计数在 800 到 1000 之间的单词列表,按计数顺序排序。我一直坚持使用计数器来查看第一个单词是否与下一个单词匹配,直到出现新单词。主要是我试图打开文件,逐字读取每个单词并在while循环中调用sort来对向量进行排序。然后,在 for 循环中遍历所有单词,如果第一个单词等于第二个 count++。我不认为这就是你保持柜台的方式。
代码如下:
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
vector<string> lines;
vector<int> second;
set<string> words;
multiset<string> multiwords;
void readLines(const char *filename)
{
string line;
ifstream infile;
infile.open(filename);
if (!infile)
{
cerr << filename << " cannot open" << endl;
return;
}
getline(infile, line);
while (!infile.eof())
{
lines.push_back(line);
getline(infile, line);
}
infile.close();
}
int binary_search(vector<string> &v, int size, int value)
{
int from = 0;
int to = size - 1;
while (from <= to)
{
int mid = (from + to) / 2;
int mid_count = multiwords.count(v[mid]);
if (value == mid_count)
return mid;
if (value < mid_count) to = mid - 1;
else from = mid + 1;
}
return from;
}
int main()
{
vector<string> words;
string x;
ifstream inFile;
int count = 0;
inFile.open("bible.txt");
if (!inFile)
{
cout << "Unable to open file";
exit(1);
}
while (inFile >> x){
sort(words.begin(), words.end());
}
for(int i = 0;i < second.size();i++)
{
if(x == x+1)
{
count++;
}
else
return;
}
inFile.close();
}
【问题讨论】:
-
对不起,我不知道为什么它在我的代码开头这样做。
-
@Chris 别担心,为你解决了这个问题
-
你真的问过问题吗?保持柜台?另外,如果这是为了家庭作业以外的事情,我很想使用 sort|uniq -c (可能使用 sed 来拆分多字行)。我可能会在编写解决方案时使用这种设计模式,但如果更复杂,哈希表会更有效。
-
你应该考虑为什么你在
for循环main()中returning。
标签: c++