C++ 按值而不是按位置擦除向量元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3385229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Erase vector element by value rather than by position?
提问by Jake Wilson
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:
如果我想删除包含“8”值的元素,我想我会这样做:
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:
因为那会擦除第四个元素。但是有没有办法根据值“8”擦除元素?喜欢:
myVector.eraseElementWhoseValueIs(8);
Or do I simply just need to iterate through all the vector elements and test their values?
还是我只需要遍历所有向量元素并测试它们的值?
回答by Georg Fritzsche
How about std::remove()
instead:
std::remove()
相反如何:
#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());
This combination is also known as the erase-remove idiom.
这种组合也称为擦除-删除习语。
回答by zneak
You can use std::find
to get an iterator to a value:
您可以使用std::find
一个迭代器来获取一个值:
#include <algorithm>
std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
if (position != myVector.end()) // == myVector.end() means the element was not found
myVector.erase(position);
回答by Naveen
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 use erase
function. Something like: myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());
. See this erasing elements from vectorfor more details.
你不能直接这样做。您需要使用std::remove
算法将要擦除的元素移动到向量的末尾,然后使用erase
函数。类似的东西:myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());
。有关更多详细信息,请参阅从矢量中擦除元素。
回答by kometen
Eric Niebler is working on a range-proposal and some of the examplesshow how to remove certain elements. Removing 8. Does create a new vector.
Eric Niebler 正在研究范围建议,其中一些示例展示了如何删除某些元素。删除 8. 创建一个新的向量。
#include <iostream>
#include <range/v3/all.hpp>
int main(int argc, char const *argv[])
{
std::vector<int> vi{2,4,6,8,10};
for (auto& i : vi) {
std::cout << i << std::endl;
}
std::cout << "-----" << std::endl;
std::vector<int> vim = vi | ranges::view::remove_if([](int i){return i == 8;});
for (auto& i : vim) {
std::cout << i << std::endl;
}
return 0;
}
outputs
产出
2
4
6
8
10
-----
2
4
6
10
2
4
6
8
10
-----
2
4
6
10