标准对矢量调用 clear 如何改变容量有什么说法?

What does the standard say about how calling clear on a vector changes the capacity?(标准对矢量调用 clear 如何改变容量有什么说法?)
本文介绍了标准对矢量调用 clear 如何改变容量有什么说法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

该网站暗示清除矢量可能会改变容量:

This website implies that clearing a vector MAY change the capacity:

http://en.cppreference.com/w/cpp/container/矢量/清除

很多实现不会在调用后释放分配的内存到clear(),有效地留下了vector的capacity()不变.

Many implementations will not release allocated memory after a call to clear(), effectively leaving the capacity() of the vector unchanged.

但根据@JamesKanze 的说法,这是错误的,清除的标准指令不会改变容量.

But according to @JamesKanze this is wrong and the standard mandates that clear will not change capacity.

标准怎么说?

推荐答案

取决于您正在查看的标准版本,clear 定义为等价于 erase(begin(), end()),或(在 C++11 中):
"销毁a中的所有元素.使所有元素失效引用、指针和迭代器a 和的元素可能会使结束迭代器."

Depending on the version of the standard you are looking at, clear is defined as the equivalent of erase(begin(), end()), or (in C++11):
"Destroys all elements in a. Invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator."

在任何情况下都不允许修改容量;以下代码由安全保证标准:

In neither case is it allowed to modify the capacity; the following code is guaranteed safe by the standard:

std::vector<int> v;
for (int i = 0; i != 5; ++ i) {
    v.push_back(i);
}
assert(v.capacity() >= 5);
v.clear();
assert(v.capacity() >= 5);
v.push_back(10);
v.push_back(11);
std::vector<int>::iterator i = v.begin() + 1;
v.push_back(12);
v.push_back(13);
*i = 42;        //  i must still be valid, because none of 
                //  the push_back would have required an
                //  increase of capacity

(C++11措辞变化的原因:委员会不想为 clear 要求 MoveAssignable,这会如果它是根据 erase 定义的,情况就是如此.)

(The reason for the change in wording in C++11: the committee didn't want to require MoveAssignable for clear, which would have been the case if it were defined in terms of erase.)

这篇关于标准对矢量调用 clear 如何改变容量有什么说法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)