下面的程序似乎每次都在最后崩溃,我假设这是因为一旦我到达i =(size-1),那么wordList [i + 1]将不会返回任何内容,返回null,或类似的东西.有什么方法吗?我纠正这是我问题的根源吗?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
using std::cin;
using std::cout; using std::endl;
using std::sort;
using std::string; using std::vector;
// Obtain a list of words and return the de-duped list
// with an accompanying word count
int main()
{
cout << "Enter a series of words separated by spaces, "
"followed by end-of-file: ";
vector<string> wordList;
string x;
while (cin >> x)
wordList.push_back(x);
typedef vector<string>::size_type vec_sz;
vec_sz size = wordList.size();
if (size == 0) {
cout << endl << "This list appears empty. "
"Please try again." << endl;
return 1;
}
sort(wordList.begin(), wordList.end());
cout << "Your word count is as follows:" << endl;
int wordCount = 1;
for (int i = 0; i != size; i++) {
if (wordList[i] == wordList[i+1]) {
wordCount++;
}
else {
cout << wordList[i] << " " << wordCount << endl;
wordCount = 1;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
两个问题.
首先,通常最好循环直到你的索引<你的大小,而不是使用!=.你有什么应该仍然在这里工作.
问题是这一行:
if (wordList[i] == wordList[i+1])
Run Code Online (Sandbox Code Playgroud)
您需要先提前停止循环(i <size - 1)或更改if语句,以便在数组中至少再有一个条目时检查wordList [i] == wordList [i + 1].
一种更简单的方法可能是从i = 1循环到i <size,并检查wordList [i-1] == wordList [i]:
for(int i = 1; i < size; i++) {
if(wordList[i - 1] == wordList[i]) {
/* same as before */
}
/* everything else the same */
}
Run Code Online (Sandbox Code Playgroud)
这将阻止您需要额外的if语句,但仍会保护您不要离开数组的边界.
编辑:
正如评论中所提到的,如果您使用所有原始代码并且只是像我提到的那样更改循环,则会出现一个1分之一的错误,但它很容易修复.
将单词计数开始为1而不是0.您知道您将始终至少有一个唯一单词.循环会在看到一个新单词时递增该计数,因此您最终会得到正确的计数.
您需要的唯一额外处理是当wordList为空时.因此,您需要快速检查单词列表是否为空,在这种情况下,计数为0.
归档时间: |
|
查看次数: |
2804 次 |
最近记录: |