运行时错误,分段错误

时间:2014-11-12 17:32:16

标签: c++ segmentation-fault

#include <cmath> 
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

/* Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next N days.

每天,您可以购买一股WOT,出售您拥有的任意数量的WOT股票,或者根本不进行任何交易。通过最佳交易策略可以获得的最大利润是多少? * /

struct data{
    int index;
    long value;
};

bool comp(const data &a,const data &b)
    {
        return a.value > b.value;
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int t;
    long n;
    int i,j;

    cin>>t;
    while(t)
        {
        t=t-1;
        cin>>n;
        long arr[n];
        long buy=0,sell=0;
        long buy_count=0;
        vector<data> copy;
        long max = 0;
        int indix=0;
        for(i=0;i<n;i++)
            {
            cin>>arr[i];
            //copy[i] = arr[i];
            data s;
            s.index = i;
            s.value = arr[i];
            copy.push_back(s);
           }
        //sort to get the maximum elements and their positions at the top
        sort(copy.begin(),copy.end(),comp);
        //cout<<copy[0].value;
        max = copy[0].value;
        indix = copy[0].index;
        int c=0;

        for(i=0;i<n;i++)
            {
            if(i<indix)
                {
                //buy a share
                buy+=arr[i];
                buy_count+=1;
            }
            else if(i==indix && i!=0)
                {

                //time to sell
                sell+= buy_count*(arr[i]);
                cout<<"in sell : sell :"<<sell<<endl;
                c++;
                cout<<"hello";// not printing , giving runtime error over here
                buy_count = 0;
                while(i>copy[c].index)
                    {
                    c++;
                }
                cout<<"hello";
                max = copy[c].value;
                indix = copy[c].index;                
            }
        }

        cout<<(sell-buy)<<endl;
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

我不知道您想要做什么,但由于此代码部分而发生分段错误:

while(i>copy[c].index)
{
    c++;
}
cout<<"hello";
max = copy[c].value;
indix = copy[c].index;

您在vector访问size而未查看size check,您需要在此处实施一些while(c < copy.size()-1 && i>copy[c].index) //! Here size()-1 because later you are using c as a index so it should always be less than size. { c++; } cout<<"hello"; max = copy[c].value; indix = copy[c].index; 。这样的事情。

{{1}}