gpt4 book ai didi

c++ - 即使根据容量()仍有未使用的空间,std::vector 能否将其数据移动到 emplace_back()处的另一个地址?

转载 作者:IT老高 更新时间:2023-10-28 12:50:47 27 4
gpt4 key购买 nike

是否保证 std::vector 仅在 size()==capacity() 并调用 push_back() 时移动其数据或 emplace_back() 或者它也可以这样做吗?

最佳答案

规范有点间接。 容量指定为:

size_type capacity() const noexcept;

Returns: The total number of elements that the vector can hold without requiring reallocation.

第二部分来自reserve:

reserve(size_type n);

Remarks: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().

由此可以得出结论,如果大小小于容量,则插入不会导致重新分配。

如果有空闲容量并且您没有显式调用 reserve,则没有单一直接声明 vector 不会重新分配。但是,[container.requirements.general]中有一个通用的容器要求:

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container.

最后,我们来描述一下插入的效果:

[insert/emplace_back/push_back:]

Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid.

综上所述:除非另有说明,否则调用成员函数不会使迭代器无效。重新分配使迭代器无效(如上面 reserve 的一部分所述),因此除非另有说明,否则调用成员函数,特别是插入,不会重新分配,为这种情况提供了一个这样的覆盖规范其中新大小超过当前容量。

关于c++ - 即使根据容量()仍有未使用的空间,std::vector 能否将其数据移动到 emplace_back()处的另一个地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37571737/

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