最大重复次数

时间:2015-09-07 20:58:02

标签: c++ string c++11 duplicates

错误:

描述资源路径位置类型 无法转换'__gnu_cxx :: __ alloc_traits> > :: value_type {aka std :: basic_string}'到'int'赋值duplicatedWords.cpp / duplicatedWords / src第42行C / C ++问题 无法转换'__gnu_cxx :: __ alloc_traits>初始化中的> :: value_type {aka std :: basic_string}'到'int'duplicatedWords.cpp / duplicatedWords / src第37行C / C ++问题 在初始化duplicatedWords.cpp / duplicatedWords / src第40行C / C ++问题中无法将'std :: basic_string'转换为'int' 不符合'operator>' (操作数类型是'__gnu_cxx :: __ alloc_traits>> :: value_type {aka std :: basic_string}'和'int')duplicatedWords.cpp / duplicatedWords / src第41行C / C ++问题

/*
Write a program to read strings from standard input
looking for duplicated words. The program should find places in the input
where one word is followed immediately by itself. Keep track of the  largest
number of times a single repetition occurs and which word is repeated.   Print
the maximum number of duplicates, or else print a message saying that no
word was repeated. For example, if the input is

how now now now brown cow cow

the output should indicate that the word now occurred three times.
*/

#include <iostream>
#include <vector>
using namespace std;

int main() {
cout << "Please enter your words " << endl;
    string words;
    vector<string> vec;

    while(cin>>words && words != "qu"){
        vec.push_back(words);

    }

    int max = vec[0];
    int result = 0;

    for(int i: vec){
        if(vec[i] > max){
        max = vec[i];
        result = i;
        }
    }

    cout<<result<<endl;
return 0;

}

1 个答案:

答案 0 :(得分:1)

如果输入已排序,我认为您的程序假定,那么对您下面的代码进行的以下修改将起作用。但是,如果输入未排序,则应使用哈希表或对输入进行排序。

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int max = 0;
    int result = 0;
    unsigned int rep_count = 1;
    string words;
    vector<string> vec;

    cout << "Please enter your words " << endl;
    while(cin>>words && words != "qu"){
        vec.push_back(words);
    }

    if (!vec.size())
        return 0;

    for(unsigned int i = 1; i < vec.size(); i++){
        if (vec[i] == vec[i-1]) {
            rep_count++;
        } else {
            rep_count = 1;
        }
        if (rep_count > max) {
            result = i;
            max = rep_count;
        }
    }
    cout<<"Word = "<<vec[result]<<", Repitition = "<<max<<endl;
    return 0;
}