标准是如何说明如何调整向量的清晰度改变容量? [英] What does the standard say about how calling clear on a vector changes the capacity?
问题描述
此网站意味着清除向量可以更改容量:
This website implies that clearing a vector MAY change the capacity:
http://en.cppreference.com/w/cpp/container/vector/clear
许多实现不会在调用
之后释放分配的内存给clear(),有效地使向量
的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.
标准说什么? p>
What does the standard say?
推荐答案
取决于您正在查看的标准版本,
清除
定义为 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中的措辞改变的原因:委员会
不想要 MoveAssignable
clear
,如果按 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
.)
这篇关于标准是如何说明如何调整向量的清晰度改变容量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!