C++ - 在映射或 vector 中插入时出现段错误

标签 c++ vector dictionary segmentation-fault

所以我将一堆值插入到一个 vector 中(我尝试了一个具有相同结果的 map )并且我的第二个 vector VectorMin 一直出现段错误。我试着取消注释,如果我只使用 VectorMax,一切都会很好。

出于某种原因,如果我尝试操作两个 vector ,我将遇到段错误。如果我取消注释其中任何一个,程序就会正确加载。

我使用的是一个 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;
}

或者应用成员函数resize。例如

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

关于C++ - 在映射或 vector 中插入时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21370389/

相关文章:

c++ - 在 C++ std::vector 构造函数中使用十六进制 0xdeadbeef

c++ - 调试断言失败。C++ vector 下标超出范围

java - 使用 Java 字典进行高效字符串搜索

c++ - 奇怪的编译错误

c++ - C和C++中return 0有什么意义?

c++ - 返回 vector 元素 C++ 的地址

c# - 是否有类型安全的有序字典替代方案?

python - 如何计算二维列表或字典列表?

c++ - 在 C++ 中查看 system() 调用的输出

C++ - 如何解决函数重载歧义