矢量下标超出范围 - 冒泡排序 - 改进

时间:2012-09-01 21:49:13

标签: c++ vector sorting

我有这段代码实现了数组的冒泡排序。 在MS VS 2012中编译它可以达到一定的目的:

UPD:我已经添加了很多检查来跟踪发生崩溃的确切位置,就像这样: 它交换数组的前两个元素,打印出一个交换了这些元素的数组,然后打印出“Checking”并崩溃,“vector subscript out of range”

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;


int Check(vector<int> Array)
{
printf ("Checking: \n");
for (int i = 0; i < Array.size(); i++)
    if((int*) Array[i] == NULL)
    {
        cerr << "Array [" << i << "] is fubared";
        return -1;
    }
}

int PrintOut(vector<int> Array)
{
printf ("Your array appears to be as follows: \n");
for (int i = 0; i < Array.size(); i++)
    printf("%d  ", Array[i]);
return 0;
}

int bubble_sort()
{
int or_size = 2;
int i, j, size, temp;

printf("Specify array size\n");
scanf_s("%d", &size);
printf(" Now, input all elements of the array \n");

vector<int> Array(size, 0);
if (size > or_size)
    Array.resize(size);

for (i = 0; i < size; i++)
{
    printf("Array [%d] is now re-initialised as ", i);
    scanf_s("%d", &temp);
    printf("\n");
    Array[i] = temp;
}

Check(Array);

PrintOut(Array);

for (i = 1; i < size; i++)
    for (j = 0; j < size-i ; j--)
    {
        printf ("Attempting to swap Array[%d], which = %d, and Array [%d], which = %d \n",j, Array[j], j+1, Array[j+1]);
        if (Array[j] > Array[j+1])
        {
            Array[j]+=Array[j+1];
            Array[j+1] = Array[j] - Array[j+1];
            Array[j] = Array[j] - Array[j+1];
            printf("Swapped \n");
        }
        PrintOut(Array);
        Check(Array);
    }

printf ("\n Your Array has been bubble_sorted and should know look like this: \n");
for (i = 0; i < size; i++)
    printf("%d ", Array[i]);

Array.clear();

return 0;
}

int main()
{
    bubble_sort();
    return 0;
}

它必须是非常简单的东西,但是我无法触及。

PS 现在没有令人尴尬的_asm; - )

1 个答案:

答案 0 :(得分:2)

您的代码对我来说有点奇怪,使用coutcin代替printfscanf会更好更多,但除此之外您还有类似的东西这样:

for (j = 0; j < size-i ; j--) {...}

因此,对于第一项j为0,然后它将递减为-1,operator[] vector的{​​{1}}取std::size_t,它将是无符号类型解释为0xFFFFFFFF,这是一个非常大的值和大的索引比矢量大小大得多,因此你得到“矢量下标超出范围”