C++ vector::clear(C++ 向量::清除)
问题描述
vector <weight> decoy;
void clear_decoy() {
decoy.clear();
vector<weight> (decoy).swap(decoy);
}
在上面的方法clear_decoy()
中,vector
是什么意思?
In the above method clear_decoy()
, what does vector<weight> (decoy).swap(decoy);
mean please?
该方法是否清除decoy
?谢谢!
Does the method clear decoy
or not? Thanks!
推荐答案
它创建一个新的 Weight
对象向量(将为空)并与 decoy
交换.
It creates a new vector of Weight
objects (which will be empty) and swaps it with decoy
.
这样做的原因是默认情况下,std::vector
The reason for this is that by default, std::vector<t>::clear
often doesn't actually reduce the storage used by a vector, it merely destroys all the objects contained there. This way, the vector has room to store more objects without reallocation in the future.
但是,有时您想修剪向量中的容量.与新创建的向量(它一直存在到它的行尾,因此在那里被销毁)交换会释放向量分配的所有内存.
Sometimes, however, you want to trim the capacity in the vector. Swapping with a newly created vector (which lives until the end of it's line, and is therefore destroyed there) frees all the memory allocated by the vector.
这篇关于C++ 向量::清除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 向量::清除
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01