重複

2015-09-07 30 views
-3

錯誤的最大數量:重複

描述資源路徑位置類型 不能轉換 '__gnu_cxx :: __ alloc_traits>> :: value_type的{又名性病:: basic_string的}' 在分配duplicatedWords.cpp/duplicatedWords '詮釋'/src line 42 C/C++問題 無法在初始化duplicateatedWords.cpp/duplicatedWords/src行中將'__gnu_cxx :: __ alloc_traits>> value_type {aka std :: basic_string}'轉換爲'int'行37 C/C++ Problem can not在初始化時將'std :: basic_string'轉換爲'int'duplicateatedWords.cpp/duplicatedWords/src line 40 C/C++問題 '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; 

}

+0

我失去了我怎麼能找到的最大重複 – TheChessDoctor

+1

首先,你有一個串矢量與你做一些事情串用它。好。然後突然,代碼的其餘部分就像vector包含整數,它可以被分配給'int'並與'>'進行比較。你在做什麼?! – deviantfan

+0

如果用戶輸入「qu」作爲第一個輸入,會發生什麼?優雅地處理該案件。 –

回答

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; 
}