2013-07-23 40 views
1

我正在學習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; 

}

+0

我有些有真正的代碼爲int的該陣列... – PlasmaHH

+1

那麼一個char isntead,做'COUT <<感覺「當前數組:\ t」的<< anArray < <「\ n」;'不會打印數組本身。它將打印陣列的**地址**。在char數組的情況下,你會得到數組的內容,但這只是因爲'''專門處理'char'數組。 –

+0

交換工作,只是取消註釋並嘗試。 –

回答

1

你顯示什麼,像0x23abcd是一個內存地址。實際上,您正在顯示指向數組中第一個元素的指針。 要在C++ 11正常顯示的陣列,最好的辦法是使用範圍,用於循環:

for(int &i : anArray) 
     std::cout << i << " "; 
+0

我不認爲我已經瞭解了有關「&」符號的知識,但我只是製作自己的循環。謝謝您的幫助 – NewtoProgramming

1

也許你應該嘗試使用一個循環來輸出數組的內容。

for(int i=0; i<anArray.size(); i++) 
    std::cout<< anArray[i] << " "; 

編輯:@awesomeyi給出的解決方案看起來更優雅。

0

,而不是代碼部分:

cout << "The current array: \t" << anArray << "\n"; 

使用本

cout << "The current array: \t"; 
for(int i=0;i<nSize;i++) 
{ 
    cout<<anArray[i]<<" "; 
} 
cout<<endl; 

這會工作,我認爲,還有一點,你所使用的標題<algorithm>你可以使用函數sort()排序的陣列在nlogn complextiy。這裏有一個例子

#include <iostream> 
#include <algorithm> 

int main() 
{ 
using namespace std; 

const int nSize = 6; 
int anArray[nSize] = {30, 60, 20, 50, 40, 10}; 

sort(anArray,anArray+6); 

    cout << "The current array: \t"; 
    for(int i=0;i<nSize;i++) 
    { 
     cout<<anArray[i]<<" "; 
    } 
    cout<<endl; 



return 0; 
}