矢量下标超出范围-冒泡排序
vector subscript out of range - bubble sort
我有一段代码,它实现了数组的气泡排序。在MS VS 2012中编译,它在一定程度上起作用:
UPD:我添加了很多检查来追踪坠机发生的确切地点,就像这样:它交换一个数组的前两个元素,打印出一个交换了这些元素的数组,然后打印出"Checking"并用"vector subscript out 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 sizen");
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;-)
for (j = size; i > 0; i--)
必须成为
for (j = size - 1; i > 0; i--)
对于维度为N的数组,索引从0变为N-1
您有一个"逐个关闭"错误:
for (i = 0; i < size; i++)
for (j = size; i > 0; i--)
// ^^^^
// j is out or range, the last valid index is size-1
if (Array[j] < Array[j-1])
swap(Array[j], Array[j-1]);
相关文章:
- 如何在C++中对数组进行冒泡排序
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 在C++中使用冒泡排序时出现意外值
- 冒泡排序中所需的交换次数,而无需实际对其进行排序
- 如何对文件中数组中的单个列进行冒泡排序?C++
- 需要关于如何将我的随机数数组连接到冒泡排序的帮助
- 对整个范围进行排序时,std::p artial_sort() 与 std::sort() 的性能?
- 是否存在用于按以下方式对两个范围进行排序和分区的标准算法?
- 冒泡排序无法对C++中的对象的动态数组进行排序
- 冒泡排序.C++
- 链表的冒泡排序
- 有没有选择排序优于冒泡排序的输入
- C++:如何使用冒泡排序来重新排列我的数据
- 冒泡排序随机数
- 向量下标超出范围-气泡排序-改进
- 矢量下标超出范围-冒泡排序
- 使用冒泡排序比较类对象
- 在c++中使用冒泡排序/交换对字符串进行排序
- 矢量下标超出范围错误,C++,冒泡排序
- 冒泡排序、选择排序和插入排序