下面的程序似乎每次崩潰在最後,我假設這是因爲一旦我到達i =(size-1),那麼wordList [我+ 1]不會返回任何東西,返回null或其他等價物。任何方式在這個?我糾正這是我問題的根源嗎?簡單'for'循環崩潰程序最後迭代
#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;
}
令人敬畏的machielo。看起來你遇到了我的兩個問題 - 出界問題以及如何捕捉列表中的最後一個單詞。只是改變'我<大小-1'並不能解決後者,但添加最終的結果。 – IanWhalen 2009-10-14 16:46:53
我很高興你發現它有幫助:) – AntonioMO 2009-10-14 16:59:51