C++ Erase vector element by value rather than by position?(C++ 按值而不是按位置擦除向量元素?)
问题描述
vector<int> myVector;
让我们说向量中的值是这个(按这个顺序):
and lets say the values in the vector are this (in this order):
5 9 2 8 0 7
如果我想删除包含值8"的元素,我想我会这样做:
If I wanted to erase the element that contains the value of "8", I think I would do this:
myVector.erase(myVector.begin()+4);
因为这会擦除第 4 个元素.但是有没有办法根据值8"擦除元素?喜欢:
Because that would erase the 4th element. But is there any way to erase an element based off of the value "8"? Like:
myVector.eraseElementWhoseValueIs(8);
还是我只需要遍历所有向量元素并测试它们的值?
Or do I simply just need to iterate through all the vector elements and test their values?
推荐答案
std::remove() 代替:
#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());
这种组合也称为擦除-删除习语.
这篇关于C++ 按值而不是按位置擦除向量元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 按值而不是按位置擦除向量元素?
基础教程推荐
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
