C++11 获取潜在内存错误,我猜-“;“双重自由或腐败”;

C++11 获取潜在内存错误,我猜-“;“双重自由或腐败”;,c++11,C++11,我只得到负数的错误,而它适用于所有正数。我不太确定这里出了什么问题。非常感谢您的帮助/指导 #include <vector> #include <iostream> #include <algorithm> int insertionSort(std::vector<int> &array){ // Count the number of shifts needed to sort the array int shift

我只得到负数的错误,而它适用于所有正数。我不太确定这里出了什么问题。非常感谢您的帮助/指导

#include <vector>
#include <iostream>
#include <algorithm>

int insertionSort(std::vector<int> &array){
    // Count the number of shifts needed to sort the array
    int shifts = 0;
    for(int i = 1; i < array.size(); i++){
        if(array[i] < array[i - 1]){
            int j = i;
            while(array[i] < array[i - 1] && i >= 0){
                shifts++;
                std::swap(array[i], array[i - 1]);
                i--;
            }
            i = j;
        }
    }
    return shifts;
}

int main(){
    std::vector<int> array = {-1, -2}; // This won't work
    //std::vector<int> array = {1, 2}; // This works
    int shifts = insertionSort(array);
    std::cout << shifts;

    return 0;
}
#包括
#包括
#包括
int insertionSort(标准::向量和数组){
//计算数组排序所需的移位数
整数移位=0;
对于(int i=1;i=0){
移位++;
交换(数组[i],数组[i-1]);
我--;
}
i=j;
}
}
返回班次;
}
int main(){
std::vector array={-1,-2};//这不起作用
//std::vector array={1,2};//这是可行的
int shifts=insertionSort(数组);

std::cout提示:你永远不希望
i
为零,或者
array[i-1]
超出范围。我不确定为什么这只适用于负数,但一个问题是内部while循环的边界。while(array[i]=0)行
while
将运行
i==0
的循环,这意味着
std::swap(数组[i],数组[i-1])
将计算
array[-1]
,这会导致未定义的行为。@DanielH:我认为这是因为只有负数的一个需要交换。正数的一个已经排序,所以它没有到达问题代码。你在for循环中迭代I,然后在循环体中弄乱I,这是在给自己设陷阱。@all-谢谢!我的错,shou我早就看过了。