gpt4 book ai didi

c++ - C++ 中 vector 的大小

转载 作者:太空宇宙 更新时间:2023-11-04 04:40:55 24 4
gpt4 key购买 nike

#include <iostream>
#include <vector>
#include "mixmax.h"//<-here, there is random number generator called mixmax
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
const unsigned long long int n=10000000;
vector < float > f(n);
vector < float > distance_1(n);
vector < float > distance_2(n);
rng_state_t s;
rng_state_t *x=&s;
seed_spbox(x,12345);//<-here we just devlare our random number generator
for(int i=0;i<n;i++)
f[i]=int(n*get_next_float(x));//,<-here we just get random numbers,like rand()
sort(f.begin(),f.end());
for(int i=0;i<n;i++)
{
distance_1[i]=f[i]-i;
distance_2[i]=(i+1)-f[i];
}
float discrep=max(*max_element(distance_1.begin(),distance_1.end()),*max_element(dis tance_2.begin(),distance_2.end()));
cout<<"discrep= "<<discrep<<endl;
cout<<"sqrt(n)*discrep= "<<discrep/sqrt(n)<<endl;
}

当我打印f.max_size()时(代码中的 vector 在上面下降)给了我这个巨大的数字4611686018427387903,但是当我取n=10000000000时,它不起作用,它给出了这个错误:

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped).

(我在windows下的Visual Studio中尝试过。)

有什么问题吗???如果 vector 不适用于大尺寸,谁能告诉我如何使用非常大尺寸的 vector 或数组???

最佳答案

引用cplusplus.com ,

std::vector::max_size

Returns the maximum number of elements that the vector can hold.

This is the maximum potential size the container can reach due to known system or library implementation limitations, but the container is by no means guaranteed to be able to reach that size: it can still fail to allocate storage at any point before that size is reached.

因此,vector 并不保证它可以容纳 max_size 元素,这只是一个实现限制。

此外,chris提到:

Well 10 GB * sizeof(float) * 3 is a ton of memory to allocate. I'm going to guess your OS isn't letting you allocate it all for a good reason.

OP问,

If vectors do not work for big sizes, can anyone tell me how can I use vectors or arrays with very big sizes ???

是的,你可以。试试RoomySTXXL .

关于c++ - C++ 中 vector 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29350287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com