【发布时间】:2013-11-07 12:25:17
【问题描述】:
我有一个任务,我被困住了。我需要创建一个程序来读取输入文件,将每个单词以及读取该单词的次数(因此是结构)存储到一个向量中。然后这些值需要按字母顺序打印出来。
我想出了一些我认为正确的方法:
struct WordInfo {
string text;
int count;
} uwords, temp;
string word;
int count = 0; //ignore this. For a different part of the task
vector<WordInfo> uwords;
while (cin >> word) {
bool flag = false;
count += 1;
for (int i = 0; i < uwords.size(); i++) {
if (uwords[i].text == word) {
flag = true;
uwords[i].count += 1;
}
}
if (flag == false) {
if (count == 1) { //stores first word into vector
uwords.push_back(WordInfo());
uwords[0].count = 1;
uwords[0].text = word;
} else {
for (int i = 0; i < uwords.size(); i++) {
if (word < uwords[i].text) {
uwords.push_back(WordInfo());
WordInfo temp = {word, 1};
uwords.insert(uwords.begin() + i, temp);
}
}
}
}
}
现在我遇到的问题是,当我运行程序时,它似乎陷入了无限循环,我不明白为什么。尽管我已经进行了足够的测试以意识到它可能在最后一个 if 语句中,但我尝试修复它并不好。任何帮助表示赞赏。干杯。
编辑:我忘了说,我们必须使用向量类,我们可以使用的东西有限,排序不是一个选项:(
【问题讨论】:
-
看看标题
<algorithm>,尤其是std::sort。 -
我猜你不能使用
std::sort,对吧? cplusplus.com/reference/algorithm/sort -
一种方法:使用以单词为键的映射并将其出现次数计为值。
-
无限循环会不会是
while(cin >> word)造成的?通常,这意味着程序正在等待用户输入。 -
查看此讨论以获取示例stackoverflow.com/questions/1380463/…