0

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

UPD:我添加了很多检查来跟踪发生崩溃的确切位置,就像这样:它交换数组的前两个元素,打印出交换了这些元素的数组,然后打印出“正在检查”并因“向量下标超出范围”而崩溃

#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 ;-)

4

1 回答 1

2

您的代码对我来说有点奇怪,使用coutandcin而不是printfandscanf但除此之外,您还有以下内容:

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

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

于 2012-09-01T22:15:02.993 回答