gpt4 book ai didi

c++ - 容量是否复制到 vector 中?

转载 作者:IT老高 更新时间:2023-10-28 13:59:30 25 4
gpt4 key购买 nike

取以下代码:

std::vector<int> a;
a.reserve(65536);
std::vector<int> b(a); //NOTE: b is constructed from a

a.reserve(65536); // no reallocation
b.reserve(65536);

容量是否被复制?最后一行会重新分配吗?标准对此有任何说明还是保持沉默?

最佳答案

Is capacity copied?

实际上,没有。我在 Clang and GCC 上在线测试过以及 MSVC他们都没有复制容量。

Will there be a reallocation on the last line?

如果容量小于要保留的参数(即它没有被复制),那么是的。

Does the standard say anything about this or is it silent?

vector.cons 中没有提供复制构造函数的定义。 .相反,我们必须查看 container.requirements

X denotes a container class containing objects of type T, a and b denote values of type X, u denotes an identifier, r denotes a non-const value of type X, and rv denotes a non-const rvalue of type X.

X u(a)

X u = a;

Requires: T is CopyInsertable into X (see below).

post: u == a

现在两个容器相等是什么意思?

a == b

== is an equivalence relation. equal(a.begin(), a.end(), b.begin(), b.end())

换句话说,因为它不需要 capacity 在比较中相等,所以没有理由复制 capacity

关于c++ - 容量是否复制到 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37639386/

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