为大数组分配内存?(c++)

Allocating memory for a large array? [c++]

本文关键字:c++ 内存 数组 分配      更新时间:2023-10-16
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