我在这篇文章中读到,a的初始容量std::vector
无法由其构造函数控制.设置它的最佳方法,如果你知道它的大小在运行时将是常量,那么似乎是:
const int size;
std::vector<T> v;
v.reserve(size);
Run Code Online (Sandbox Code Playgroud)
但是,既然T
是一个大类,我很乐意使用构造函数的初始化参数std::vector<T> v(size, T());
.那么只分配我需要的内存而不必手动迭代元素来初始化它们的最佳方法是什么?
std::vector<T> v;
v.reserve(size);
for(T t : v) t = T(); // `has to call T::operator= (that may not even be defined)
Run Code Online (Sandbox Code Playgroud)
要么
std::vector<T> v(size, T()); // may allocate more memory than I need..
v.shrink_to_fit(); // ..then deallocate it immediately (pointless)
Run Code Online (Sandbox Code Playgroud)
什么是最接近我的理想:
std::vector<T> v(size, T(), /*capacity =*/ size);
Run Code Online (Sandbox Code Playgroud)
[编辑]:根据你的答案,我需要更准确的是v
用每个构建的size
实例填充默认构造函数,而不是复制.我怎么能这样做,因为在编译时不知道我不能使用初始化列表?T
T
size
奖励:顺便说一下,为什么没有办法选择矢量的初始容量?
奖金优先:
奖励:顺便说一下,为什么没有办法选择矢量的初始容量?
因为班上的设计师从未认为它足够重要.
我知道以后没有实施:
std::vector<T> v(size, T());
Run Code Online (Sandbox Code Playgroud)
以下断言不成立:
assert(v.capacity() == size);
Run Code Online (Sandbox Code Playgroud)
保留标准不保证.但它似乎确实是事实上的标准.
然而,人们无法将这一点传说转移到std::string
.
如果你想积极要求capacity() == size()
在施工后,你可以使用shrink_to_fit()
.话虽如此,shrink_to_fit()
标准不能保证工作,如果它确实做了任何事情,它会暂时加倍你的内存需求.这种用法可能如下:
std::vector<T> v(size, T());
if (v.capacity() > v.size())
v.shrink_to_fit(); // If executed and successful, this will allocate a new buffer
if (v.capacity() > v.size())
// now what?
Run Code Online (Sandbox Code Playgroud)
使用reserve()
不再有效.后reserve()
,capacity()
是大于或等于自变量reserve
,如果重新分配发生; 并等于之前的capacity()
其他值.
归档时间: |
|
查看次数: |
1046 次 |
最近记录: |