C ++中矢量的初始容量(Initial capacity of vector in C++)

编程入门 行业动态 更新时间:2024-10-28 09:23:08
C ++中矢量的初始容量(Initial capacity of vector in C++)

使用默认构架创建的std::vector的capacity()是多少? 我知道size()是零。 我们可以声明一个默认构造的向量不会调用堆内存分配?

这样,可以使用单个分配来创建一个具有任意保留的数组,如std::vector<int> iv; iv.reserve(2345); std::vector<int> iv; iv.reserve(2345); 。 让我们说,由于某种原因,我不想在2345年启动size() 。

例如,在Linux上(g ++ 4.4.5,kernel 2.6.32 amd64)

#include <iostream> #include <vector> int main() { using namespace std; cout << vector<int>().capacity() << "," << vector<int>(10).capacity() << endl; return 0; }

打印0,10 。 这是一个规则,还是STL厂商依赖?

What is the capacity() of an std::vector which is created using the default constuctor? I know that the size() is zero. Can we state that a default constructed vector does not call heap memory allocation?

This way it would be possible to create an array with an arbitrary reserve using a single allocation, like std::vector<int> iv; iv.reserve(2345);. Let's say that for some reason, I do not want to start the size() on 2345.

For example, on Linux (g++ 4.4.5, kernel 2.6.32 amd64)

#include <iostream> #include <vector> int main() { using namespace std; cout << vector<int>().capacity() << "," << vector<int>(10).capacity() << endl; return 0; }

printed 0,10. Is it a rule, or is it STL vendor dependent?

最满意答案

该标准没有规定容器的初始capacity应该是什么,因此您依赖于实现。 一个共同的实施将开始在零的能力,但不能保证。 另一方面,没有办法改善你的策略std::vector<int> iv; iv.reserve(2345); std::vector<int> iv; iv.reserve(2345); 所以坚持下去

The standard doesn't specify what the initial capacity of a container should be, so you're relying on the implementation. A common implementation will start the capacity at zero, but there's no guarantee. On the other hand there's no way to better your strategy of std::vector<int> iv; iv.reserve(2345); so stick with it.

更多推荐

本文发布于:2023-07-18 04:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154964.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矢量   容量   Initial   capacity   vector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!