简体   繁体   English

如何将内存分配给大小为10 ^ 9的二维数组

[英]How to allocate memory to a 2d array of size 10^9

I want a 2d array to take inputs upto 10^9. 我希望2d数组的输入最多为10 ^ 9。 Rows and Columns can go upto 10^9. 行和列最多可以达到10 ^ 9。 How shall I assign it since dynamic allocation is giving me a run-time error. 我应该如何分配它,因为动态分配给我一个运行时错误。

I assigned the memory dynamically but I am getting a run-time error when input is 10^5 or more. 我动态分配了内存,但是当输入为10 ^ 5或更多时,我会遇到运行时错误。 I know array will use 10^9 x 10^9 x 4 bytes of memory which my heap can't handle it, so How do i assign it. 我知道数组将使用10 ^ 9 x 10 ^ 9 x 4字节的内存,我的堆无法处理它,所以如何分配它。

long long int n,m,k,ans=0;
        cin>>n>>m>>k;
        long long int**a=new long long int*[n+2];
        for(long long i=0;i<=n+2;i++){
            a[i]=new long long int[m+2];
        }
        for(long long int i=0;i<=n+1;i++){
            for(long long int j=0;j<=m+1;j++)
                a[i][j]=0;
        }

I expect the code to take input when rows and columns are 10^5. 我希望代码在行和列为10 ^ 5时接受输入。 However I am getting following: 但是我正在关注:

terminate called after throwing an instance of std::bad_alloc

10^9 even with 1 byte elements is a gigabyte, a 2D array is 10^9^2 or an exabyte. 甚至具有1个字节元素的10 ^ 9也是一个千兆字节,一个2D数组是10 ^ 9 ^ 2或一个EB。 With 64bit integers that is 8 exabytes. 使用64位整数,即8艾字节。 So you need to rethink this. 因此,您需要重新考虑这一点。 I assume you won't actually have data in the vast majority of that? 我认为您实际上将没有绝大多数数据?

You could for example use an std::map or std::unordered_map . 例如,您可以使用std::mapstd::unordered_map

unsigned char bytes[] = { 10, 55, 255 };
struct pair_hash
{
    std::size_t operator() (const std::pair<int, int> &p)const
    {
        return std::hash<int>()(p.first) ^ std::hash<int>()(p.first); // Possibly want a better hash
    }
};
std::unordered_map<std::pair<int, int>, long long, pair_hash> map;

You will need to define a hash for it. 您将需要为其定义哈希。 In this case you could also combine the two integers into the high and low bits, as a long long is generally large enough to hold two ints. 在这种情况下,您也可以将两个整数组合为高位和低位,因为long long通常足够容纳两个int。

std::unordered_map<long long, long long> map;

There are other ways to do "sparse arrays" and can depend a lot on your data, for example do you expect "clusters" or everything evenly distributed? 还有其他方法可以执行“稀疏数组”,并且可能在很大程度上取决于您的数据,例如,您是否期望“集群”或所有内容均匀分布? What is the read/write pattern? 什么是读/写模式?

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

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