为了账号安全,请及时绑定邮箱和手机立即绑定

使用STL vector的几种清空容器(删除)办法?

使用STL vector的几种清空容器(删除)办法?

千万里不及你 2019-02-05 10:06:21
使用STL vector的几种清空容器(删除)办法
查看完整描述

2 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

先写一个循环来迭代容器中的元素,如果迭代元素是要删除的元素,则删除之。
代码如下所示:
vector<int> intContainer;

for(vector<int>::iterator is = intContainer.begin(); it != intContainer.end(); ++it)
{
if ( *it == 25)
intContainer.erase(it);
}。借助remove算法来达到删除元素的目的。

vector<int> intContainer;

size_t before_size = intContainer.size();
remove(intContainer.begin(), intContainer.end(), 25);
size_t after_size = intContainer.size();
运行程序以后发现before_size和after_size是一样的,说明元素并没有被真正删除。写出以上程序,是处于对remove算法的不了解而致。STL中remove算法会将不该删除的元素前移,然后返回一个迭代器,该迭代器指向的是那个应该删除的元素,仅此而已。所以如果要真正删除这一元素,在调用remove之后还必须调用erase,这就是STL容器元素删除的"erase_remove"的惯用法。

vector<int> intContainer;
intContainer.erase( remove(intContainer.begin(), intContainer.end(), 25), intContainer.end());

erase-remove的惯用法适用于连续内存容器,比如vector,deque和string,它也同样适用于list,但是并不是推荐的方法,因为使用list成员函数remove会更高效,
代码如下:
list<int> list_int;
....
list_int.remove(25);
标准关联容器没有remove成员函数,使用STL算法的remove函数时编译同不过。所以上述remove形式对于标准关联容器并不适用。
在这种情况下,解决办法就是调用erase:

map<int, int> mapContainer;
...
mapContainer.erase(25);
对于标准关联容器,这样的元素删除方式是简单有效的,时间复杂度为O(logn).
当需要删除的不是某一个元素,而是具备某一条件的元素的时候,只需要将remove替换成remove_if即可

bool Is2BeRemove(int value)
{
return value < 25;
}
vector<int> nVec;
list<int> nList;
....
nVec.erase(remove_if(nVec.begin(), nVec.end(), Is2BeRemove), nVec.end());
nList.remove_if(Is2BeRemove);
删除容器中具有特定值的元素:
如果容器是ector、string或者deque,使用erase-remove的惯用法。如果容器是list,使用list::remove。如果容器是标准关联容器,使用它的erase成员函数。
删除容器中满足某些条件的元素:
如果容器是ector、string或者deque,使用erase-remove_if的惯用法。如果容器是list,使用list::remove_if。如果容器是标准关联容器,使用remove_copy_if & swap 组合算法。



查看完整回答
反对 回复 2019-03-14
?
慕仙森

TA贡献1827条经验 获得超7个赞

第一种办法使用 clear ,清空元素,但不回收空间
vecInt.clear();
j=vecInt.capacity();//j=512i=vecInt.size();//i=0第二种办法使用 erase循环删除,结果同上vector<int::iteratoriter=vecInt.begin();for(;iter!=vecInt.end();){iter=vecInt.erase(iter);}j=vecInt.capacity();//j=512i=vecInt.size();//i=0
erase在每次操作时,迭代器指针会整体前移1,就是每次都会搬全部数据,所以vector不适合做频繁删除的容器
第三种办法 最简单的使用swap,清除元素并回收内存vector<int().swap(vecInt); //清除容器并最小化它的容量,//vecInt
.swap(vector<int())
; 另一种写法
j=vecInt.capacity();//j=0i=vecInt.size();//i=0该语句是由vector<int(vecInt).swap(vecInt)的变体而来,一下解释引自csdn:
std::vector<T(v).swap(v);的作用相当于:{std::vector<T temp(v);//1
temp.swap(v);//2}第一句产生一个和v内容一模一样的vector,只不过temp的容量是恰好满足其大小的
第二句把v和temp交换
然后temp就自动解析掉了
这样写的作用是:把v的容量缩小到最佳值
该例中执行这句时,



查看完整回答
反对 回复 2019-03-14
  • 2 回答
  • 0 关注
  • 1652 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信