2015-09-07 25 views
-3

我被困在這個uva問題中,我認爲我的算法是正確的,但程序在運行時崩潰,我找不出問題在哪裏,但我認爲它是與迭代器? ?!請任何幫助!Stuck at什麼是中位數UVa 10107

代碼:

#include <iostream> 
#include <algorithm> 
#include <vector> 
using namespace std; 
int main() 
{ 
    int n, R, L; 

    long long idx, aver; 
    std::vector<long long> v; 
    std::vector<long long>::iterator it; 

    while(cin >> n) 
    { 
     it=v.begin(); 
     v.push_back(n); 
     std::sort(v.begin(), v.end()); 

     if(v.size() == 1) 
     { 
      std::cout << *it << std::endl; 
     } 
     else if(v.size() % 2 == 0) 
     { 
      L=v.size()/2 - 1; 
      R=v.size()/2; 

      aver = (*(it + L) + *(it + R))/2; 

      std::cout<< aver << std::endl; 
     } 
     else 
     { 
      idx = v.size()/2; 
      aver = *(it + idx); 

      std::cout << aver << std::endl; 
     } 
    } 

    return 0; 
} 

Problem link

Ideone link

+3

a)使用調試器來找出它崩潰。 b)在這裏描述你的程序應該做什麼。 – deviantfan

+1

@deviantfan c)不要在愚蠢的在線編程競賽中浪費你的時間! –

+0

我是新來的問題解決,我還不能調試,謝謝。 –

回答

1

我得到了它,我終於被錄取了,這個問題是與迭代器,這指出了v.begin()當載體是在循環的第一次迭代時爲空,所以程序崩潰了。在做了第一個push_back()之後,我使迭代器指向vector的開始位置,在這種情況下vector不是空的。

權代碼:

#include<iostream> 
#include<algorithm> 
#include <vector> 
using namespace std; 
int main() 
{ 
    int n,R,L; 
    long long idx,aver; 
    vector<long long>v; 
    vector<long long>::iterator it; 

    while(cin>>n) 
    { 

     v.push_back(n); 
     it=v.begin(); 
     sort(v.begin(),v.end()); 



     if(v.size()==1){ 
      cout<<*it<<endl; 
     } 
     else if(v.size()%2==0) 
     { 
      L=v.size()/2-1; 
      R=v.size()/2; 

      aver=(*(it+L)+*(it+R))/2; 

      cout<<aver<<endl; 
     } 
     else 
     { 
      idx=v.size()/2; 
      aver=*(it+idx); 

      cout<<aver<<endl; 
     } 
    } 
    return 0; 
} 

Ideone link