lreis2415 / SEIMS

Spatially Explicit Integrated Modeling System --- open-source, cross-platform, and high performance computation
https://lreis2415.github.io/SEIMS/
GNU General Public License v3.0
50 stars 34 forks source link

How to destructor STL container correctly?/如何正确使用erase释放STL容器? #20

Open crazyzlj opened 7 years ago

crazyzlj commented 7 years ago

STL中容器的释放:到底如何使用erase()

STL中erase()函数的功能是用来删除容器中元素的,在析构函数中释放容器内内存资源尤其重要。

然而,看似简单的动作,对不同类型的容器,内部缺做了截然不同的事情,而且不同编译器的实现也有差异。

crazyzlj commented 6 years ago

Use auto when declaring iterators (C++11).

/// 链表容器,以map为例
for (auto it = map1.begin(); it != map1.end(); ) {
    //it = map1.erase(it); /// VS支持,Intel C++ 12,GCC 4.4.6不支持
    map1.erase(it++); /// 推荐用法
}

/// 数组容器,以vector为例
for (auto it = vec1.begin(); it != vecs.end(); ) {
    it = vec1.erase(it); /// 推荐用法
    //vec1.erase(it++); /// Intel C++ 12,GCC 4.4.6支持,VS不支持
    //vec1.erase(it); /// Intel C++, GCC,及VS2005支持,但是不推荐
}
crazyzlj commented 2 years ago

clear() vs erase()

Takes std::vector as an example.

vector::clear()

The vector::clear() function is used to remove all the elements of the vector container, thus making it size 0. Its time complexity is O(N). All elements are destroyed one by one.

vector::erase()

The vector::erase() function is used to remove elements from a container from the specified position or range. Its time complexity O(N^2) in the worst case as an erase takes linear time.

When to use what?

clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using the clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.

简言之,当需要全部删除容器中元素时要用clear(),当然,需要注意的是,如果容器元素需要释放内存,一定要在clear()之前逐个释放;当需要删除容器中已知位置的某个或某些元素时,用erase()

Reference: vector-erase-and-clear-in-cpp