c++ - vector 下标超出范围 - 冒泡排序 - 改进

标签 c++ vector sorting

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

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

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

它一定是非常简单的东西,但我够不着。

附言 现在没有尴尬的 _asm ;-)

最佳答案

你的代码对我来说有点奇怪,最好使用 coutcin 而不是 printf scanf 但除此之外你还有这样的东西:

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

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

关于c++ - vector 下标超出范围 - 冒泡排序 - 改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12231707/

相关文章:

c++ - C++ 中 vector 下标超出范围

c++ - STL vector 性能

arrays - 如何根据 ruby​​ 2.3.0 中的值对哈希键进行排序

python - 对 Pandas 数据框的列进行排序

c++ - 找到可能的最大内存分配

c++ - 寻找更好的C++类工厂

Java日期周期比较

javascript - 为什么 Array.sort 有时会比较某些值对两次?

c++ - C++ 中的日期/时间解析

c++ - 让 Boost 在 centos 5.5 中工作