我需要在我的项目中创建一个非常大的数组。我尝试了3种方法,但都是bad_alloc
。我无法理解,因为我的电脑的内存是10GB。为什么bad_alloc在新建数组,重新调整向量和push_back向量时?
这是我在MSVC2015 x86模式下的实现。
CODE1
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
const long long MEM_SIZE = 1LL * 1024LL * 1024LL * 1024LL; // available memory 1GB
typedef struct MyClass {
int a;
unsigned char b,c,d;
size_t e,f;
double g, h;
};
int main() {
MyClass *mc = new MyClass[MEM_SIZE/sizeof(MyClass)];
cout << "done!" << endl;
return 0;
}
CODE2
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
const long long MEM_SIZE = 1LL * 1024LL * 1024LL * 1024LL; // available memory 1GB
typedef struct MyClass {
int a;
unsigned char b,c,d;
size_t e,f;
double g, h;
};
int main() {
vector<MyClass> myv;
myv.resize(MEM_SIZE/sizeof(MyClass));
cout << "done!" << endl;
return 0;
}
CODE3
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
const long long MEM_SIZE = 1LL * 1024LL * 1024LL * 1024LL; // available memory 1GB
typedef struct MyClass {
int a;
unsigned char b,c,d;
size_t e,f;
double g, h;
};
int main() {
vector<MyClass> myv;
MyClass tmp;
for (int i = 0; i < 12000000; i++){
tmp.a = i;
myv.push_back(tmp);
}
cout << "done!" << endl;
return 0;
}
MyClass
的大小是32字节,我将可用内存设置为1GB,所以数组长度为1GB/32B = 33554432。
至于CODE1和CODE2,数组大小为1GB,远远小于PC的RAM,为什么bad_alloc
?
至于CODE3,我知道push_back
的时候,vector的容量会翻倍,但是它也比PC的RAM少。在CODE3中,当i==11958657
坠毁。
但是,当我建立和运行在x64模式,一切都很好。据我所知,x86的堆大约是2GB,为什么我的1GB阵列崩溃?
我该如何做x86模式?
这是一个合法的问题,我不明白downvotes。 –
可能是'vector :: max_size()'可以提供帮助。 [链接](http://www.cplusplus.com/reference/vector/vector/max_size/) –
使用'std :: deque'而不是'std :: vector'有什么区别? –