2017-07-07 40 views
1
#include<iostream> 
using namespace std; 
int main() 
{ 
    int s; 
    cin>>s; 
    int t=3; 
    int maxValue,imax[t],maxIndex,arr[s]; 
    for(int i=0; i<s; i++){ 
     cin>>arr[i]; 
    } 
    maxValue=arr[0]; 
    for(int i=0;i<s;i++){ 
     if(arr[i]>maxValue){ 
      maxValue=arr[i]; 
      imax[0] = i; 
     } 
    } 
    maxValue=arr[0]; 
    for(int i=0;i<s;i++){ 
     if (i == imax[0]) { continue; } 
     if(arr[i]>maxValue){ 
      maxValue=arr[i]; 
      imax[1] = i; 
     } 
    } 
    maxValue=arr[0]; 
    for(int i=0;i<s;i++){ 
     if (i == imax[0]) { continue; } 
     if (i == imax[1]) { continue; } 
     if(arr[i]>maxValue){ 
      maxValue=arr[i]; 
      imax[2] = i; 
     } 
    } 
    cout<<"First biggest number:"<<arr[imax[0]]<<"\n"; 
    cout<<"Second biggest number:"<<arr[imax[1]]<<"\n"; 
    cout<<"Third biggest number:"<<arr[imax[2]]; 
    return 0; 
} 

該程序必須返回這個數組中最大的樹數,但是我不知道爲什麼當我引入例如五個數字(121,34,56,67,545)並且編譯器是返回545然後崩潰。 預先感謝您的回答。排列中最大的三個數字

+0

'arr [s]'不是標準的C++。你不能使用'std :: vector '而不是?另外,你如何處理前3位數字包含重複的情況? – Bathsheba

+1

正如@Bathsheba所說,使用'std :: vector'。然後查找'std :: nth_element'。 –

+0

當我開始編譯我介紹作爲例子五個​​數字(121,34,56,67,545)和編譯器是返回545然後分解 –

回答

1

的問題是,迭代循環之前,首先設置maxValue是陣列中的第一個元素。只有至少有一個元素大於當前的maxValue時,imax纔會更新。但是,如果第一個元素在某種程度上是maxValue,那麼imax將永遠不會被設置,這將被初始化,導致最後的段錯誤。

在你的代碼中,找到最大元素545後,第二大元素從未找到,因爲121是數組中的第一個元素。因此,在打印出545之後,imax[1]未初始化並且程序崩潰。

0

您在線

cout<<"First biggest number:"<<arr[imax[0]]<<"\n"; 
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n"; 
cout<<"Third biggest number:"<<arr[imax[2]]; 

如果有小於3不同號碼輸入,一些imax數組元素將不被初始化,使用未初始化數組值。此外,如果輸入數組爲空,則imax將不會被初始化。

因此,在表達式arr[imax[1]]中,您閱讀了arr的索引元素,該索引未初始化,並且可能是一些非常大的數字。它可如果你聲明iarr作爲

int imax[t] = {}; 

這將零初始化數組的所有元素,並會防止崩潰是固定的。

您的程序也不檢查輸入數組中的元素數量,因此如果輸入數字少於三個,arr[2]也會打印未初始化的值。

下面是使用STL算法和std :: vector的適當解決方案。它適用於任何數量的t - 您可以輕鬆將其更改爲打印最大的10個數字。它還具有內存高效性 - 它不需要存儲整個輸入數組,因此您可以使用它處理大量輸入。

#include <algorithm> 
#include <iostream> 
#include <vector> 

int main() { 
    int s; 
    std::cin >> s; 

    unsigned t = 3; 
    std::vector<int> max_numbers; 
    max_numbers.reserve(t + 1); 

    for (int i = 0; i < s; ++i) { 
    int number; 
    if (std::cin >> number) { //Check basic input errors 
     max_numbers.push_back(number); // Add number to top-3 list 

     // Sort elements in descending order 
     std::sort(max_numbers.begin(), max_numbers.end(), std::greater<int>()); 

     // Remove duplicates 
     max_numbers.erase(std::unique(max_numbers.begin(), max_numbers.end()), 
         max_numbers.end()); 

     // Remove excess elements 
     if (max_numbers.size() > t) { 
     max_numbers.resize(t); 
     } 
    } 
    } 

    std::cout << "Biggest " << t << " numbers are" << std::endl; 
    for (int i : max_numbers) { 
    std::cout << i << std::endl; 
    } 
} 
+0

謝謝你的回答。 –