C ++向量:: clear [英] C++ vector::clear
问题描述
vector <weight> decoy;
void clear_decoy() {
decoy.clear();
vector<weight> (decoy).swap(decoy);
}
在上述方法 clear_decoy c $ c>,
vector
是什么意思?
In the above method clear_decoy()
, what does vector<weight> (decoy).swap(decoy);
mean please?
方法是否清除 decoy
?感谢!
推荐答案
它创建一个新的向量 Weight
将会是空的),并与 decoy
交换它。
It creates a new vector of Weight
objects (which will be empty) and swaps it with decoy
.
这样做的原因是默认情况下, std :: vector< t> :: clear
通常不会实际减少向量使用的存储,它只是破坏了那里包含的所有对象。这样,向量就有空间来存储更多对象,而不会在将来重新分配。
The reason for this is that by default, std::vector<t>::clear
often doesn't actually reduce the storage used by a vector, it merely destroys all the objects contained there. This way, the vector has room to store more objects without reallocation in the future.
然而,有时候,你想修剪向量中的容量。使用新创建的向量(它生存到它的行尾,并因此被销毁)释放所有由向量分配的内存。
Sometimes, however, you want to trim the capacity in the vector. Swapping with a newly created vector (which lives until the end of it's line, and is therefore destroyed there) frees all the memory allocated by the vector.
这篇关于C ++向量:: clear的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!