[英]C++ std::vector clear all elements
Consider a std::vector
: 考虑一个
std::vector
:
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
Would vec.clear()
and vec = std::vector<int>()
do the same job? vec.clear()
和vec = std::vector<int>()
做同样的工作吗? What about the deallocation in second case? 第二种情况下的解除分配怎么样?
vec.clear()
clears all elements from the vector, leaving you with a guarantee of vec.size() == 0
. vec.clear()
清除向量中的所有元素,保证vec.size() == 0
。
vec = std::vector<int>()
calls the copy/move(Since C++11) assignment operator , this replaces the contents of vec
with that of other
. vec = std::vector<int>()
调用copy / move(从C ++ 11开始)赋值运算符,这将vec
的内容替换为other
。 other
in this case is a newly constructed empty vector<int>
which means that it's the same effect as vec.clear();
在这种情况下,
other
是新构造的空vector<int>
,这意味着它与vec.clear();
具有相同的效果vec.clear();
. 。 The only difference is that
clear()
doesn't affect the vector's capacity while re-assigning does, it resets it. 唯一的区别是
clear()
不会影响向量的容量,而重新分配时,它会重置它。
The old elements are deallocated properly just as they would with clear()
. 旧元素正确释放,就像使用
clear()
。
Note that vec.clear()
is always as fast and without the optimizer doing it's work most likely faster than constructing a new vector and assigning it to vec
. 请注意,
vec.clear()
始终如此快速,并且没有优化器执行它的工作最有可能比构造新向量并将其分配给vec
更快。
They are different: 它们是不同的:
clear
is guaranteed to not change capacity. clear
是保证不会改变的能力。
Move assignment is not guaranteed to change capacity to zero, but it may and will in a typical implementation. 移动分配不能保证将容量更改为零,但在典型的实现中可能会也会如此。
The clear
guarantee is by this rule: clear
保证是这个规则:
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 ofcapacity()
在调用
reserve()
之后发生的插入期间不会发生重新分配,直到插入使向量的大小大于capacity()
的值reserve()
为止
Post conditions of clear
: 发布条件
clear
:
Erases all elements in the container.
擦除容器中的所有元素。 Post:
a.empty()
returnstrue
发布:
a.empty()
返回true
Post condition of assignment: 转让条件:
a = rv;
a shall be equal to the value that
rv
had before this assignmenta应等于
rv
在此赋值之前的值
a = il;
Assigns the range
[il.begin(),il.end())
into a.将范围
[il.begin(),il.end())
分配给a。 All existing elements of a are either assigned to or destroyed.a的所有现有元素都被分配或销毁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.