C++数组排序,内存错误

C++ Array Sorting, Memory Error?

本文关键字:错误 内存 数组排序 C++      更新时间:2023-10-16

我正在学习C++编程,但在基本的数组排序程序中遇到了问题。我的代码似乎没有抛出任何编译器错误——VisualStudio2012没有显示任何错误。此外,它看起来和我在教程(learncpp.com)中找到的代码一模一样

输出应该在其选择排序的每一步都显示一个数组。然而,我一直得到不同的随机字母和数字输出。这是内存问题吗?还是别的什么?

此外,注释掉的"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;

}

您显示的内容,比如0x23abcd,是一个内存地址。实际上,您正在显示指向数组中第一个元素的指针。要在C++11中正确显示数组,最好的方法是使用循环的范围:

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

也许您应该尝试使用循环来输出数组的内容。

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

编辑:@awesomeyi给出的解决方案看起来更优雅。

而不是代码部分:

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;
}