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.

测试

clear demo++view raw
1
2
3
4
5
6
7
8
9
10
11
12
void Method1_clear() {
vector<int> data = ConstructVector();
// 打印 vector 容器的大小和容量
std::cout << "original: size = " << data.size()
<< " ; capacity = " << data.capacity() << std::endl;

data.clear();

// 再次打印更新后 vector 容器的大小和容量
std::cout << "new: size = " << data.size()
<< " ; capacity = " << data.capacity() << std::endl;
}

输出

1
2
3
Method 1
original: size = 5 ; capacity = 5
new: size = 0 ; capacity = 5

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.

测试

erase demo++view raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void Method2_erase() {
vector<int> data = ConstructVector();
// 打印 vector 容器的大小和容量
std::cout << "original: size = " << data.size()
<< " ; capacity = " << data.capacity() << std::endl;

for (auto iter = data.begin(); iter != data.end();) {
iter = data.erase(iter);
}

// 再次打印更新后 vector 容器的大小和容量
std::cout << "new: size = " << data.size()
<< " ; capacity = " << data.capacity() << std::endl;

vector<int> data1 = ConstructVector();
data1.erase(data1.begin(), data1.begin() + 2);

std::cout << "new: size = " << data1.size()
<< " ; capacity = " << data1.capacity() << std::endl;
}

输出

1
2
3
4
Method 2
original: size = 5 ; capacity = 5
new: size = 0 ; capacity = 5
new: size = 3 ; capacity = 5

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.

测试

erase demo++view raw
1
2
3
4
5
6
7
8
9
10
11
12
void Method3_swap() {
vector<int> data = ConstructVector();
// 打印 vector 容器的大小和容量
std::cout << "original: size = " << data.size()
<< " ; capacity = " << data.capacity() << std::endl;

vector<int>().swap(data);

// 再次打印更新后 vector 容器的大小和容量
std::cout << "new: size = " << data.size()
<< " ; capacity = " << data.capacity() << std::endl;
}

输出

1
2
3
Method 3
original: size = 5 ; capacity = 5
new: size = 0 ; capacity = 0

区别

  • vector 内存占用空间只会增长,不会减小。比如你首先分配了 10,000 个字节,然后 erase 掉后面 9,999 个,则虽然有效元素只有一个,但是内存占用仍为 10,000 个。所有空间在 vector 析构时回收。
  • 如果想清空原来数据占用的空间,我们可以通过交换技术 swap, 就是通过交换函数 swap (),使得 vector 离开其自身的作用域,从而强制释放 vector 所占的内存空间.

源码

源码下载

源码下载

编译

1
2
cd 文件下载目录
g++ vector_clear.cpp -o test --std=c++14

Reference