使用结构数组初始化结构的向量

时间:2013-10-20 15:19:58

标签: c++ vector

我尝试了正常的方法

typedef struct
{
int distance; //distance to the next stop
int fuel;     //the fuel at the stop
}stopInfo;

int main()
{
    vector<stopInfo> swapper;   
    int numCases,i,initFuel,distance,numStops;
    stopInfo *I;
    scanf("%d",&numCases);
    for(i=0;i<numCases;i++)
    {   
        scanf("%d",&numStops);      
        I=(stopInfo *)malloc(sizeof(stopInfo)*numStops+2);  
        for(i=0;i<numStops;i++)   scanf("%d %d",&I[i].distance,&I[i].fuel);             
        scanf("%d %d",&distance,&initFuel); 
        I[numStops].fuel=initFuel;  I[numStops].distance=distance; //for starting point
        I[numStops+1].fuel=0;  I[numStops+1].distance=0;           //for destination
        //sort in decresing order of distance.

            vector<stopInfo> v;  v.assign(I,I+numStops+2);

            sort(v.begin(),v.end(),customCompare);
        for(i=0;i<numStops+2;i++)     //copy back in array
        {
            I[i].distance=v[i].distance;
            I[i].fuel=v[i].fuel;    
        }       

        for(i=0;i<numStops+1;i++)
        I[i].distance=I[i].distance-I[i+1].distance;        
        printf("%d\n",fxMemoWrap(I,numStops,initFuel)); 
    }
    return 0;
}

但是它会出错

  

a.out:malloc.c:2451:sYSMALLOc:断言`(old_top ==(((mbinptr)(((char *)&amp;((av) - &gt; bins [((1) - 1) * 2])) - __builtin_offsetof(struct malloc_chunk,fd))))&amp;&amp; old_size == 0)|| ((unsigned long)(old_size)&gt; =(unsigned long)(((__ builtin_offsetof(struct malloc_chunk,fd_nextsize))+((2 *(sizeof(size_t))) - 1))&amp;〜((2 * (sizeof(size_t))) - 1)))&amp;&amp;((old_top) - &gt; size&amp; 0x1)&amp;&amp;((unsigned long)old_end&amp; pagemask)== 0)'失败。< / p>

0 个答案:

没有答案