之前写代码的时候,定义了一个queue<int> q,当想清楚q中的元素时,才发现q是没有clear方法的。后来看了一下资料,才发现queue是基于deque实现的,deque有clear方法,queue没有。
今儿在stackoverflow发现了这么一段话:
A common idiom for clearing standard containers is swapping with an empty version of the container:
void clear( std::queue<int> &q )
{
std::queue<int> empty;
std::swap( q, empty );
}
It is also the only way of actually clearing the memory held inside some containers (std::vector)
Better yet isstd::queue<int>().swap(q)。
stack也没有clear,其清楚方法为stack<int>().swap(st);
本文介绍了如何清除C++标准库中的queue和stack容器。由于这两种容器类型并未提供clear方法,文章提供了通过交换(empty swap)的方式清空queue和stack的有效方法。
458

被折叠的 条评论
为什么被折叠?



