为大数组分配内存?(c++)
Allocating memory for a large array? [c++]
int *tthousand = new int[10000];
int *hthousand = new int[100000];
static int tmillion[10000000];
你好,
我正在尝试动态分配内存的一系列数组。然后用从0到10,000,000的随机数填充这些数组。然后,使用快速排序/选择排序对它们进行排序。我遇到的问题是,每当到达"tmillion"数组时,程序将运行一段时间,然后发生堆栈溢出。
我试着这样写:
int *tmillion = new int[10000000];
和.
static int tmillion[10000000];
我一定错过了一些简单的东西。抱歉,我对c++还是有点陌生。
想法吗?
仅供将来参考。自从c++ 11在标准库中引入了std::array。它应该比类c的内置数组更好。
的例子:
#include <array>
std::array<int, 10000000> myArray;
// fill the array with data
std::sort(myArray.begin(); myArray.end()); // sorts data using default operator <
关于这个容器的更多信息可以在Bjarne主页上找到:http://www.stroustrup.com/C++11FAQ.html#std-array
标准容器数组是定义在的元素的固定大小的随机访问序列。除了保存元素所需的空间外,它没有空间开销,它不使用自由存储,它可以用初始化列表初始化,它知道自己的大小(元素数量),除非你显式地要求它转换为指针,否则它不会转换为指针。换句话说,它非常像一个内置数组,但没有这些问题。
额外的例子:
#include <array> // std::array
#include <algorithm> // std::sort
#include <iostream> // std::cout
int main()
{
std::array<int, 10> myArray = {8, 3, 6, 7}; // array with 10 elements but create it with declaring only first 4 elements
std::cout << "BEFORE SORT:" << std::endl;
for (const auto& element : myArray)
{
std::cout << element << std::endl;
}
std::sort(myArray.begin(), myArray.end()); // sorts data using default operator <
std::cout << "AFTER SORT:" << std::endl;
for (const auto& element : myArray)
{
std::cout << element << std::endl;
}
}
输出:
BEFORE SORT:
8
3
6
7
0
0
0
0
0
0
AFTER SORT:
0
0
0
0
0
0
3
6
7
8
相关文章:
- 将字符串存储在c++中的稳定内存中
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- Win32编译器选项和内存分配
- 当vector是tje全局变量时,c++中vector的内存管理
- 带内存和隔离功能的SQLite
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 迭代时从向量和内存中删除对象
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 为什么示例代码访问IUnknown中已删除的内存
- 如何在C++类内存结构中创建"spacer"?
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 类型总是使用其大小存储在内存中吗
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存