How do I remove an item from a stl vector with a certain value?(如何从具有特定值的 stl 向量中删除项目?)
问题描述
我正在查看 stl vector 的 API 文档,并注意到 vector 类上没有允许删除具有特定值的元素的方法.这似乎是一个常见的操作,而且没有内置的方法来执行此操作似乎很奇怪.
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
does not 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 向量中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从具有特定值的 stl 向量中删除项目?


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09