gpt4 book ai didi

c++ - 设置 *both* 元素和 std::vector 的初始容量

转载 作者:太空狗 更新时间:2023-10-29 20:03:52 24 4
gpt4 key购买 nike

我读过 this post std::vector的初始容量无法由其构造函数控制。如果您知道它的大小在运行时将保持不变,那么设置它的最佳方法似乎是:

const int size;
std::vector<T> v;
v.reserve(size);

但是,由于 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)

std::vector<T> v(size, T());  // may allocate more memory than I need..
v.shrink_to_fit(); // ..then deallocate it immediately (pointless)

什么最接近我的理想:

std::vector<T> v(size, T(), /*capacity =*/ size);

[编辑]:从你的回答来看,我更需要的是 v填充 size T 的实例, 每个构建与 T的默认构造函数,未复制。我该怎么做,因为在 size 时我无法使用初始化列表在编译时不知道吗?


奖励:顺便说一下,为什么没有办法选择 vector 的初始容量?

最佳答案

奖金第一:

Bonus: By the way, why is there no way choosing the initial capacity of a vector?

因为类的设计者从未认为它重要到需要包含。


我知道之后没有实现:

std::vector<T> v(size, T());

以下断言不成立:

assert(v.capacity() == size);

标准不保证它能保持。但它似乎确实是事实上的标准。

但是,不能将这一知识转移到 std::string


如果你想在构建后明确要求capacity() == size(),你可以使用shr​​ink_to_fit()。话虽这么说,shr​​ink_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?

reserve() 的使用不再有效。在 reserve() 之后,如果发生重新分配,capacity() 大于 或等于 reserve 的参数;否则等于 capacity() 的先前值。

关于c++ - 设置 *both* 元素和 std::vector 的初始容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24846348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com