简体   繁体   English

为大型阵列分配内存? [c++]

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

int *tthousand = new int[10000];  
int *hthousand = new int[100000];
static int tmillion[10000000];

Hello there,你好呀,

I'm trying to dynamically allocate memory for a series of arrays.我正在尝试为一系列数组动态分配内存。 These arrays are then populated with random numbers ranging from 0 to 10,000,000.然后用 0 到 10,000,000 的随机数填充这些数组。 From there, they are sorted using a quicksort/selection sort.从那里,它们使用快速排序/选择排序进行排序。 The problem I'm running into is that whenever the "tmillion" array is reached, the program will run for a time and then a stack overflow occurs.我遇到的问题是,只要达到“tmillion”数组,程序就会运行一段时间,然后发生堆栈溢出。

I've tried writing it as:我试过把它写成:

int *tmillion = new int[10000000];

and..和..

static int tmillion[10000000];

I must be missing something simple.我一定错过了一些简单的东西。 Apologies, I'm still a bit new to C++.抱歉,我对 C++ 还是有点陌生​​。

Thoughts?想法?

Just for future reference.仅供日后参考。 Since C++11 std::array was introduced in Standard Library.由于 C++11 std::array 是在标准库中引入的。 It should be preferred than C-like built-in array.它应该比类 C 的内置数组更受欢迎。

Example:例子:

#include <array>
std::array<int, 10000000> myArray;
// fill the array with data
std::sort(myArray.begin(); myArray.end()); // sorts data using default operator <

More information about this container can be found on Bjarne homepage: http://www.stroustrup.com/C++11FAQ.html#std-array关于这个容器的更多信息可以在 Bjarne 主页上找到: http : //www.stroustrup.com/C++11FAQ.html#std-array

The standard container array is a fixed-sized random-access sequence of elements defined in .标准容器数组是 中定义的固定大小的随机访问元素序列。 It has no space overheads beyond what it needs to hold its elements, it does not use free store, it can be initialized with an initializer list, it knows its size (number of elements), and doesn't convert to a pointer unless you explicitly ask it to.它没有超出保存元素所需的空间开销,它不使用自由存储,它可以使用初始化列表进行初始化,它知道它的大小(元素数量),并且不会转换为指针,除非你明确要求它。 In other words, it is very much like a built-in array without the problems.换句话说,它非常像一个没有问题的内置数组。

Additional example:附加示例:

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

Output:输出:

BEFORE SORT:
8
3
6
7
0
0
0
0
0
0
AFTER SORT:
0
0
0
0
0
0
3
6
7
8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM