C++数组排序,内存错误
C++ Array Sorting, Memory Error?
我正在学习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;
}
相关文章:
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 内存错误低于在C++年实现埃拉托色尼筛分时的预期
- 共享内存:MapViewOfFile 返回错误 5
- 将 vector<vector<int>> 传递到函数中会产生内存错误
- 释放动态内存时C++错误
- 我有一个线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)错误.我认为这是由于内存管理不好.我可以
- 复制内存给出分段错误
- C++程序错误:malloc():内存损坏
- 在我的以下代码中获取 MLE(内存限制错误).尝试解决 ROUND C 2019(问题 A-摆动行走)启动问题
- 为什么删除分配的阵列会导致内存错误?
- 需要找到3个小错误-内存错误
- 错误:内存位置的 std::length_error
- 修复了瓦尔格林德错误内存泄漏的错误
- 错误:“内存集”未在此范围内声明
- OpenCV 2.4.5运行时错误内存
- OpenCV错误:内存不足
- STL映射,设置错误:内存超出分配块的末尾
- GLUT:致命错误:内存不足
- MPI错误:内存不足-有哪些解决方案选项