2012-09-01 96 views
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現在;-)

+0

if((int *)Array [i] == NULL)你這樣做?! – ForEveR

+0

好吧,我懷疑如果它確實是== NULL,那麼有些地方是錯誤的。 – Chiffa

+0

爲什麼爲空?爲什麼不'Array [i] == 0'? – ForEveR

回答

2

你的代碼是一個有點奇怪對我來說,這是更好,更使用coutcin代替printfscanf但你身邊有這樣的事情:

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

所以對於第一項j是0,那麼它會遞減爲-1並且由於vectoroperator[]採取std::size_t並且它是一個無符號類型將是INTE詮釋爲0xFFFFFFFF,這是一個非常大的值和大的索引,比你的向量大得多,因此你得到了「向量下標超出範圍」

+0

謝謝,我會研究一下。這聽起來很簡單,它應該是正確的。 – Chiffa

+0

是的,你是對的:它應該是真正的j ++。現在它工作得很好。非常感謝 – Chiffa