1
我寫了一個應該對數組進行排序的小程序。當我運行它時,它完成了它的工作,但似乎給數組添加了一個隨機數。我也會看到標題中顯示的錯誤。運行時檢查失敗#02,添加到陣列的隨機數
#include "stdafx.h"
#include <iostream>
#include <algorithm>
void printArray(int nArray[], int nSize) {
using namespace std;
for (int jjj = 0; jjj <= nSize; jjj++)
cout << nArray[jjj] << " ";
cout << endl;
}
void sortArray(int nArray[], int nSize, bool bPrint) { // bPrint is used to wether print after every step or not
for (int nStartIndex = 0; nStartIndex < nSize; nStartIndex++) { // Durch jeden Teil des Arrays gehen
int nSmallestIndex = nStartIndex; // Den aktuellen Startindex als kleinsten nehmen
for (int nCurrentIndex = nStartIndex + 1; nCurrentIndex <= nSize; nCurrentIndex++) {
if (nArray[nCurrentIndex] < nArray[nSmallestIndex])
nSmallestIndex = nCurrentIndex;
}
using namespace std;
swap(nArray[nStartIndex], nArray[nSmallestIndex]);
if (bPrint) {
cout << "Swapping " << nArray[nStartIndex] << " and " << nArray[nSmallestIndex] << endl;
printArray(nArray, nSize);
}
}
}
int main() {
const int nSize = 7;
int nArray[nSize] = { 3, 1, 5, 8, 2, 4, 6 };
printArray(nArray, nSize);
sortArray(nArray, nSize, true);
std::cout << std::endl;
system("pause");
return 0;
}
只要使用std :: sort()。 –
'nCurrentIndex <= nSize'不正確。 –