簡體   English   中英

C ++-在地圖或矢量中插入時出現分段錯誤

[英]C++ - Segmentation Fault when Inserting in Map or Vector

所以我將一堆值插入向量(我嘗試了具有相同結果的地圖),並且在第二個向量VectorMin上不斷遇到分割錯誤。 我嘗試取消注釋,如果我僅使用VectorMax,那么一切都很好。

由於某種原因,如果我嘗試同時操縱兩個向量,則會遇到分割錯誤。 如果我沒有任何評論,則程序將正確加載。

我正在使用3.5mb文件,該文件包含1000行,每行362個值。

std::vector<float> vectorMax, vectorMin;

void Parser::isMaxMinVector(float value, int index){

    //if the index of the vector is not yet used
    if (index >= vectorMax.size()){
       vectorMax.push_back(value);
    }

    if(index >= vectorMin.size()){
       vectorMin.push_back(value);
    }

    //if new vector is larger, then overwrite it
    //if(vectorMax[index] > value) vectorMax[index] = value;
    //if(vectorMin[index] < value) vectorMin[index] = value;
}


void Parser::parseLine(char* line){
    std::vector<float> vectors;
    char* point;

    char* tk1 = strtok(line, ",");
    char* tk2 = strtok(NULL, ",");

    int i=0;

    if(tk1 == NULL || tk2 == NULL) return;

    float x = strtof(tk1, NULL);
    float y = strtof(tk2, NULL);

    XYPair pair = XYPair(x, y);
    isMaxXY(x,y);

    while(point=strtok(NULL, ",")){
        //convert the token to float
        float f_point = strtof(point, NULL);
        //push the float to the vector
        vectors.push_back(f_point);
        isMaxMinVector(f_point, i);
        i++;
    }
}

您幾次更改了您的帖子代碼。 不過,此代碼段

if (index >= vectorMax.size()){
    vectorMax[index] = value;
}

無效,因為您使用索引> = size()的不存在的元素。 我想你是說

if ( !vectorMax.empty() && index < vectorMax.size()){
    vectorMax[index] = value;
}

或應用成員函數調整大小。 例如

if (index >= vectorMax.size()){
    vectorMax.resize( index + 1 ); 
    vectorMax[index] = value; 
}

您確定了向量的大小,以便為它們分配足夠的存儲空間嗎? 如果該元素沒有值,則IIRC operator []不會調整其未定義行為的大小。 如果您想要稀疏的東西,則必須使用類似地圖的東西。

我認為來自莫斯科的弗拉德(Vlad)回答如下是正確的。

   if (index >= vectorMax.size()){
      vectorMax[index] = value;
     }

如果您沒有在其他任何地方觸摸矢量,那么它將起作用:

//if the index of the vector is not yet used
if (index >= vectorMax.size()){
   vectorMax.push_back(value);
   // update index here:
   index = vectorMax.size();
}

if(index >= vectorMin.size()){
   vectorMin.push_back(value);
   // and here:
   index = vectorMax.size();
}
//if new vector is larger, then overwrite it
if(vectorMax[index] > value) vectorMax[index] = value;
if(vectorMin[index] < value) vectorMin[index] = value;

但是,與此有關的問題是,在索引更改的情況下, index值將不會更新。 您可以通過在插入簽名中使用int &index來更改它。 弗拉德的方法對此要好得多。 另一方面,還不清楚向量中的其他元素包含什么(例如,如果您要創建vectorMin偽像)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM