简体   繁体   English

将std向量重新分配给默认构造函数向量是否是擦除的好方法?

[英]Is reassigning a std vector to default constructor vector a good way to erase?

There are so many questions and answers about clearing an std::vector and I'm wondering why, in all the ones I read, no one just says: 关于清除std::vector问题和答案如此之多,我想知道为什么在我阅读的所有文章中,没有人会说:

existingVector = std::vector<whatever>();

Is this not a simple way to clear a vector? 这不是清除向量的简单方法吗?

It is indeed simple, but there is a simpler and more straightforward way: 它确实很简单,但是有一个更简单,更直接的方法:

existingVector.clear();

You could also do: 您也可以这样做:

existingVector.resize(0);

But I like the first approach as it does exactly what it says it does. 但是我喜欢第一种方法,因为它完全按照它说的去做。

Similarly, I prefer checking if(myVec.empty()) instead of if(myVec.size() == 0) 同样,我更喜欢检查if(myVec.empty())而不是if(myVec.size() == 0)

Update: If you want a "true reset", ie you not only want the size to become 0 but also the capacity then there are a couple of things you could do. 更新:如果您想要“真正的重置”,即您不仅希望大小变为0,还希望容量变为零,那么您可以做几件事。

  1. shrink to fit 缩小以适合

     vec.clear(); vec.shrink_to_fit(); 

As the comments correctly point out though, shrink_to_fit, too, is a non-binding request which the compiler may ignore. 正如注释正确指出的那样,shrink_to_fit也是一个非绑定请求,编译器可能会忽略它。

  1. swap with a newly constructed vector 与新构建的向量交换

     vector<whatever>().swap(vec); 

Assigning is okay, but an optimizing implementation may be allowed to hold on to the raw memory buffer, to avoid reallocation. 分配是可以的,但是可以允许优化实现保留原始内存缓冲区,以避免重新分配。

Conventional wisdom for forcefully freeing the vector, is "swapping with a temporary": 强制释放向量的传统观点是“用临时交换”:

#include <vector>
#include <iostream>


int main() {

    std::vector<int> a(256);

    std::vector<int>().swap(a);

    std::cout << a.size() << " / " << a.capacity();

    return 0;
}

The above will always print 0 / <minimum_capacity_for_vec_impl> because the vectors must swap their internal buffers. 上面的代码将始终输出0 / <minimum_capacity_for_vec_impl>因为向量必须交换其内部缓冲区。 The temporary is then immediately destroyed, freeing the memory along with it. 然后,临时文件立即被销毁,从而释放内存。


<minimum_capacity_for_vec_impl> Will usually be 0, since the default constructor is noexcept , and by that virtue shuoldn't do dynamic memory allocation. <minimum_capacity_for_vec_impl> 通常为0,因为默认构造函数为noexcept ,因此shuoldn不会进行动态内存分配。 But Library implementors can be creative sometimes with their optimizations. 但是,图书馆实施者有时可以通过优化来发挥创造力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM