我必须解决一个任务,因此它会打印一组字符串的最小值,最大值和模式。首先,我将字符串存储在一个向量中,而不是对它们进行排序,然后打印向量的第一个和最后一个元素,这很好。但我很难找到它们的模式。这是我写的代码。
#include<stdafx.h>
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
vector<string>words;
cout << "Please enter some words. When finished, just enter 'stop'.\n";
string ant;
int count = 0;
int max = 0;
while (cin >> ant) {
if (ant != "stop") {
words.push_back(ant);
}
else
break;
}
sort(words.begin(), words.end());
cout << "The min of the entered words is " << words[0] << "\n";
cout << "The max of the entered words is " << words.back() << "\n";
}
到目前为止这很好。它按我的意愿完成工作。但问题出现在我必须找到字符串的模式。我在网上找到了一些用于查找给定整数模式的代码,它适用于整数。我试图修改它的字符串,但我无法让它工作。这是代码:
for (string test = 0; test<words.size(); ++test) {
if (words[test] == words[test + 1]) {
count++;
}
else if (words[test] != words[test + 1]) {
if (count>max) {
max = count;
mode = words[test];
}
count = 0;
}
}
这给了我很多错误,我不知道从哪里开始。我认为问题在于这不是进行字符串迭代的正确方法。我找到了关于字符串迭代的一些解释,但它让我感到困惑。任何帮助将不胜感激。
答案 0 :(得分:0)
找到输入单词模式的算法的修改版本是正确的。我唯一可以说的是,count
和max
是C ++中的关键字,因此您必须更改名称以避免不良影响。另外,请不要忘记将mode
声明为string
类型。
只需稍加修改代码,就可以了;
#include<iostream>
#include<vector>
#include <map>
#include<string>
#include<algorithm>
using namespace std;
int main() {
vector<string>words;
cout << "Please enter some words. When finished, just enter 'stop'.\n";
string ant;
int count = 0;
int max = 0;
while (cin >> ant) {
if (ant != "stop") {
words.push_back(ant);
}
else
break;
}
sort(words.begin(), words.end());
cout << "The min of the entered words is " << words[0] << "\n";
cout << "The max of the entered words is " << words.back() << "\n";
//Finding the mode of the entered words
int _count = 0;
int _max = 0;
string mode;
for (unsigned int test = 0, j = 1; test<words.size(); test++, j++) {
if (words[test] == words[j]) {
_count++;
}
else if (words[test] != words[j]) {
if (_count>_max) {
_max = _count;
mode = words[test];
}
_count = 0;
}
}
cout << "The mode of the entered words is " << mode;
}