停留在什么是中值 UVa 10107

Stuck at What is the median UVa 10107

我被困在这个 uva 问题上,我认为我的算法是正确的,但程序在 运行 上崩溃了,我不知道问题出在哪里,但我认为它与迭代器有关??!请帮忙!!!

代码:

#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

我知道了我终于被接受了,问题出在迭代器上,当循环的第一次迭代时向量为空时它指向 v.begin(),因此程序崩溃了。在执行第一个 push_back() 之后,我使迭代器指向向量的开头,在这种情况下向量不为空。

正确的代码:

#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