C++ vector 清空元素的三种方法 (有源码)
[toc]
clear
- A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function.
测试
1 | void Method1_clear() { |
输出
1 | Method 1 |
erase
Removes from the vector either a single element (position) or a range of elements ([first,last)).
An iterator pointing to the new location of the element that followed the last element erased by the function call.
测试
1 | void Method2_erase() { |
输出
1 | Method 2 |
swap
Exchanges the content of the container by the content of x, which is another vector object of the same type. Sizes may differ.
After the call to this member function, the elements in this container are those which were in x before the call, and the elements of x are those which were in this. All iterators, references and pointers remain valid for the swapped objects.
测试
1 | void Method3_swap() { |
输出
1 | Method 3 |
区别
- vector 内存占用空间只会增长,不会减小。比如你首先分配了 10,000 个字节,然后 erase 掉后面 9,999 个,则虽然有效元素只有一个,但是内存占用仍为 10,000 个。所有空间在 vector 析构时回收。
- 如果想清空原来数据占用的空间,我们可以通过交换技术 swap, 就是通过交换函数 swap (),使得 vector 离开其自身的作用域,从而强制释放 vector 所占的内存空间.
源码
源码下载
编译
1 | cd 文件下载目录 |