【发布时间】:2018-11-29 17:13:29
【问题描述】:
如何让程序打印出重复次数最多的单词?现在它打印如下:
输入: 苹果香蕉苹果苹果
输出:
苹果出现了 3 次
香蕉出现了 1 次
int main() {
string words;
vector<string> stringHolder;
while (cin >> words)
{
stringHolder.push_back(words);
}
sort(stringHolder.begin(), stringHolder.end());
int vSize = stringHolder.size();
if (vSize == 0) {
cout << " no words ";
}
int wordCount = 1;
words = stringHolder[0];
for (int i = 1; i<vSize; i++) {
if (words != stringHolder[i]) {
cout << words << " appeared " << wordCount << " times" << endl;
wordCount = 0;
words = stringHolder[i];
}
wordCount++;
}
cout << words << " appeared " << wordCount << " times" << endl;
system("pause");
}
【问题讨论】:
-
我建议使用
std::map<string,int>来跟踪单词计数器。 -
std::map确实是最简单的解决方案。如果由于特定原因(作业...)不允许您使用它,请对数组进行排序stringHolder,然后使用单个for循环以线性方式计数 -
已经有排序功能
-
@πάνταῥεῖ 如何使用 std::map
将单词添加到地图中。我无法使用 map::insert