C++ std::vector 清除所有元素

C++ std::vector clear all elements

考虑 std::vector:

std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);

vec.clear()vec = std::vector<int>()会做同样的工作吗?第二种情况下的重新分配怎么样?

vec.clear() 清除向量中的所有元素,保证 vec.size() == 0.

vec = std::vector<int>() 调用 copy/move(C++11 起)赋值运算符,这会将 vec 的内容替换为 other 的内容。 other 在这种情况下是一个新构造的空 vector<int> 这意味着它与 vec.clear(); 的效果相同。唯一的区别是 clear() 不会影响向量的容量,而重新分配会影响向量的容量,它会重置它。

旧元素被正确释放,就像它们在 clear() 中一样。

请注意,vec.clear() 总是一样快,并且在没有优化器的情况下,它的工作速度很可能比构建新向量并将其分配给 vec 更快。

它们不同:

clear保证不换容量

移动分配不能保证将容量更改为零,但在典型的实现中它可能并且将会。


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 of capacity()

Post条件clear:

Erases all elements in the container. Post: a.empty() returns true

Post赋值条件:

a = rv;

a shall be equal to the value that rv had before this assignment

a = il;

Assigns the range [il.begin(),il.end()) into a. All existing elements of a are either assigned to or destroyed.