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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:44:04  来源:igfitidea点击:

C++ Erase vector element by value rather than by position?

c++vectorstleraseerase-remove-idiom

提问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::findto 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::removealgorithm to move the element to be erased to the end of the vector and then use erasefunction. 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