C++按值而不是按位置擦除向量元素?
vector<int> myVector;
假设向量中的值是这样的(按此顺序):
5 9 2 8 0 7
如果我想删除包含值“8”的元素,我想我会这样做:
myVector.erase(myVector.begin()+4);
因为这会删除第四个元素。但是有什么方法可以删除基于值“8”的元素吗?比如:
myVector.eraseElementWhoseValueIs(8);
或者我只需要迭代所有向量元素并测试它们的值?
vector<int> myVector;
and lets say the values in the vector are this (in this order):
5 9 2 8 0 7
If I wanted to erase the element that contains the value of "8", I think I would do this:
myVector.erase(myVector.begin()+4);
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样
std::remove()
:此组合也称为擦除-删除习惯用法。
How about
std::remove()
instead:This combination is also known as the erase-remove idiom.
您可以使用 std::find 来获取值的迭代器:
You can use
std::find
to get an iterator to a value:你不能直接这样做。您需要使用
std::remove
算法将要擦除的元素移动到向量的末尾,然后使用erase
函数。类似:myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());
。有关更多详细信息,请参阅从向量中删除元素。You can not do that directly. You need to use
std::remove
algorithm to move the element to be erased to the end of the vector and then useerase
function. Something like:myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());
. See this erasing elements from vector for more details.Eric Niebler 正在研究范围提案,一些示例展示了如何删除某些元素。删除 8. 确实会创建一个新向量。
输出
Eric Niebler is working on a range-proposal and some of the examples show how to remove certain elements. Removing 8. Does create a new vector.
outputs