如何从stl向量中删除具有某个值的项目? [英] How do I remove an item from a stl vector with a certain value?

查看:134
本文介绍了如何从stl向量中删除具有某个值的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看stl向量的API文档,并注意到在向量类上没有允许删除具有特定值的元素的方法。这似乎是一个常见的操作,看起来很奇怪,没有内置的方法来做到这一点。

I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.

推荐答案

std :: remove实际上不会从容器中擦除元素,但它会返回新的结束迭代器,它可以传递给container_type :: erase来删除现在位于容器末尾的额外元素:

std::remove doesn't actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase to do the REAL removal of the extra elements that are now at the end of the container:

std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());

这篇关于如何从stl向量中删除具有某个值的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆