环境:
内存限制:512 MB
运行以下代码,将顺利完成:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main() {
long long N;
vector<long long> set3;
for(long long i = 1; i < 20000000; ++i) {
set3.push_back(i);
}
cout << "count:" << set3.size() << " capacity:" << set3.capacity() << endl;
vector<long long> set5;
for(long long i = 1; i < 12000000; ++i) {
set5.push_back(i);
}
cout << "count:" << set5.size() << " capacity:" << set5.capacity() << endl;
return 0;
}
如果我交换set3和set5,它将因异常而失败:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
以下是失败的代码:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main() {
long long N;
vector<long long> set5;
for(long long i = 1; i < 12000000; ++i) {
set5.push_back(i);
}
cout << "count:" << set5.size() << " capacity:" << set5.capacity() << endl;
vector<long long> set3;
for(long long i = 1; i < 20000000; ++i) {
set3.push_back(i);
}
cout << "count:" << set3.size() << " capacity:" << set3.capacity() << endl;
return 0;
}
为什么吗
这是另一个成功案例,我们甚至可以通过vector :: assign
成功分配370 MB#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main() {
long long N;
vector<long long> set5;
for(long long i = 1; i < 12000000; ++i) {
set5.push_back(i);
}
cout << "count:" << set5.size() << " capacity:" << set5.capacity() << endl;
vector<long long> set3;
//set3.assign(49807360, 0); // fail: 49807360 * 64 / 8 / 1024 / 1024 == 380 MB
set3.assign(48496640, 0); // succeed: 48496640 * 64 / 8 / 1024 / 1024 == 370 MB
/*
for(long long i = 1; i < 20000000; ++i) {
set3.push_back(i);
}
*/
cout << "count:" << set3.size() << " capacity:" << set3.capacity() << endl;
return 0;
}
为什么矢量的push_back(导致内存从128MB增加到256MB)的内存分配在384 MB上失败;而在相同的384 MB上vector.assign( 370MB ,远大于256 MB)会成功吗?
这是内存碎片问题吗?
在成功案例中:
Allocate for set3: (by vector::push_back)
256 MB out of 512 MB ---- Good;
then allocate for set5: (by vector::push_back)
128 MB out of the remaining 256 MB ---- Good;
在失败的情况下:
Allocate for set5: (by vector::push_back)
128 MB out of 512 MB ---- Good;
then allocate for set3: (by vector::push_back)
256 MB out of the remaining 384 MB ---- Fail.
在另一个成功案例中:
Allocate for set5: (by vector::push_back)
128 MB out of 512 MB ---- Good;
then allocate for set3: (by vector::assign)
370 MB out of the remaining 384 MB ---- Good.