加速C++中的练习3-3让我对循环设计有两个更广泛的问题。练习的挑战是将任意数量的单词读入矢量,然后输出给定单词在该输入中出现的次数。我已经包含下面我相关代码:循环设计:计数和随后的代码复制
string currentWord = words[0];
words_sz currentWordCount = 1;
// invariant: we have counted i of the current words in the vector
for (words_sz i = 1; i < size; ++i) {
if (currentWord != words[i]) {
cout << currentWord << ": " << currentWordCount << endl;
currentWord = words[i];
currentWordCount = 0;
}
++currentWordCount;
}
cout << currentWord << ": " << currentWordCount << endl;
注意输出代码必须循环处理的最后一个字之外再出现。我意识到我可以将它移动到一个函数,如果我担心重复代码的复杂性,只需调用函数两次。
问题1:这种解决方法是常见的吗?有没有一种典型的方法来重构循环以避免这种重复?
问题2:尽管我的解决方案非常简单,但我习惯于从零开始计算。有没有一种更可接受的方式来编写这个循环?或者这是最佳实施?
'std :: map word_count; for(const std :: string&word:words){word_count [word] ++; } for(std :: pair count:word_count){std :: cout << count.first <<“:”<< count.second <<“\ n”; }'。或者其他的东西。 –
2012-03-22 04:39:12
代码被破坏,或者您的问题描述已关闭。你在这里计算连续出现的次数,因为'[“cat”,“dog”,“cat”]'会输出:'cat:1','dog:1','cat:1'。 – 2012-03-22 07:58:36