如何知道向量的实际最大大小?(不使用 std::vector::max_size) [英] How can I know the real maximum size of a vector? (Not using std::vector::max_size)
问题描述
在一个在线课程中,我正在学习向量.在其中一个例子中,他们解释说: std::vector::max_size()
应该给我向量可以达到的最大尺寸.我决定测试一下:
On an online course I am learning about vectors. In one of the examples they explained that: std::vector::max_size()
should give me the maximum size the vector can reach. I decided to test it:
#include <iostream>
#include <exception>
#include <vector>
int main(void) {
std::vector <int> nums;
int max = nums.max_size();
std::cout << "Max: " << max << std::endl;
for (int i = 0; i < max; i++) {
try {
nums.push_back(i);
}
catch (std::bad_alloc ex) {
std::cerr << ex.what() << std::endl;
std::cout << "Failed at: " << i << std::endl;
break;
}
}
return 0;
}
这是运行它的结果:
Max: 1073741823
bad allocation
Failed at: 204324850
短了 869416973 个整数.
It was 869416973 ints short.
所以我开始在谷歌上搜索它.这里 我读到它返回容器可以达到的最大潜在尺寸",并补充说但绝不能保证容器能够达到那个大小".我会想象它会失败,但不会那么多.在失败之前,它只走了 1/5 的路.为什么 std::vector::max_size
这么差?我认为更重要的是,有没有办法真正知道向量的潜在大小?
So I started googling it. Here I read that it returns the "the maximum potential size the container can reach", and adds "but the container is by no means guaranteed to be able to reach that size". I would have imagined that it would fail, but not by that much. It just got 1/5 of the way before failing. Why is std::vector::max_size
so off? And what I see of more importance, is there a way of really knowing the potential size of a vector?
推荐答案
注意 max_size
函数返回元素的理论最大数量,它没有说明所需的内存量.
Note that the max_size
function returns a theoretical maximum number of elements, it doesn't say anything about the amount of memory needed.
如果我们假设 sizeof(int) == 4
(很常见)那么 204324850
元素将需要 817299400
字节的 连续的内存(将近 780 MiB).
If we assume that sizeof(int) == 4
(pretty common) then 204324850
elements would need 817299400
bytes of contiguous memory (that's almost 780 MiB).
您会收到 bad_alloc
异常,因为向量根本无法分配足够的内存来容纳所有元素.
You get a bad_alloc
exception because the vector simply can't allocate enough memory to hold all the elements.
这篇关于如何知道向量的实际最大大小?(不使用 std::vector::max_size)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!