我正在學習C++編程,並且遇到了基本的數組排序程序問題。我的代碼似乎不會引發任何編譯器錯誤 - VisualStudio2012不顯示任何錯誤。此外,它看起來就像我在我的教程(learncpp.com)上找到的代碼。C++數組排序,內存錯誤?
輸出應該在其選擇排序的每一步顯示一個數組。不過,我不斷得到隨機字母和數字的不同輸出。這是一個記憶問題嗎?或者是其他東西?
此外,註釋掉'if'循環是我如何交換數組元素在1行而不是2行代碼。這將工作排序?
#include "stdafx.h"
#include <iostream>
#include <algorithm>
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
const int nSize = 6;
int anArray[nSize] = {30, 60, 20, 50, 40, 10};
for (int nStartIndex = 0; nStartIndex < nSize; nStartIndex++){
int nSmallestIndex = nStartIndex;
for (int nCurrentIndex = nSmallestIndex + 1; nCurrentIndex < nSize; nCurrentIndex++){
/* if (anArray[nCurrentIndex] < anArray[nSmallestIndex])
swap(anArray[nSmallestIndex], anArray[nCurrentIndex]);
*/
if (anArray[nCurrentIndex] < anArray[nSmallestIndex])
nSmallestIndex = nCurrentIndex;
}
swap(anArray[nStartIndex], anArray[nSmallestIndex]);
cout << "The current array: \t" << anArray << "\n";
}
return 0;
}
我有些有真正的代碼爲int的該陣列... – PlasmaHH
那麼一個char isntead,做'COUT <<感覺「當前數組:\ t」的<< anArray < <「\ n」;'不會打印數組本身。它將打印陣列的**地址**。在char數組的情況下,你會得到數組的內容,但這只是因爲'''專門處理'char'數組。 –
交換工作,只是取消註釋並嘗試。 –