C++ 根据属性值擦除struct向量中的元素

C++ 根据属性值擦除struct向量中的元素,c++,stl,vector,struct,C++,Stl,Vector,Struct,可能重复: 我的结构如下: struct V { int x; int y; }: 我有一个结构元素的stl向量 vector<struct V> v1; 可以将与适当的谓词一起使用: bool my_predicate(const V& item) { // apply some logic and return true or false return item.x == 42; } #include <algorithm> std:

可能重复:

我的结构如下:

struct V {
 int x;
 int y;
}:
我有一个结构元素的stl向量

vector<struct V> v1;
可以将与适当的谓词一起使用:

bool my_predicate(const V& item)
{
   // apply some logic and return true or false
   return item.x == 42;
}

#include <algorithm>

std::vector<V> v1 = ....;
v1.erase( remove_if(v1.begin(), v1.end(), my_predicate), v1.end() );

您可能希望使用remove\u if(没有erase\u if:您如何实现一个不知道从哪个容器中删除的擦除?)

下面是一个(经过编译、测试的)程序,演示了如何做到这一点:

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

struct V
{
    int x; 
    int y;
};

bool y_less_than_5(V const &v)
{
    return v.y < 5;
}


int main()
{
    vector<V> vec;
    V v;
    v.x = 4;  v.y = 1; vec.push_back(v);
    v.x = 17; v.y = 3; vec.push_back(v);
    v.x = 21; v.y = 5; vec.push_back(v);
    v.x = 36; v.y = 7; vec.push_back(v);
    v.x = 25; v.y = 9; vec.push_back(v);

    vec.erase(
        remove_if(vec.begin(), vec.end(), y_less_than_5),
        vec.end());

    for(vector<V>::const_iterator it = vec.begin(); it != vec.end(); ++it)
    {
        cout << "[" << it->x << "," << it->y << "]" << endl;
    }
}

您提供谓词的确切方法可能有所不同,但这是一个不同的问题;)

在C++11中,使用lambda非常简单:

v1.erase( std::remove_if( v1.begin(), v1.end(), [](V const& v) { return v.y<value; }),
          v1.end());

v1.erase(std::remove_if(v1.begin(),v1.end(),[](V const&V){返回代码v>代码> STD::EraseIIF:<代码>。在C++标准中没有这样的函数。我认为代码> STD::/ReaveIVI/Eng>只用于列表。@ ReSML:<代码:ST:::ReaveVII:I/COD>只用于列表。<代码>:DeVelyIF,<代码>是全局的。它们也做了不同的事情。列表版本,因为它知道它的容器,能够交流。实际调整容器的大小。
std::remove_if
只是将元素移动到传递给它的迭代器所划定的范围的前面。@rpsml:有一个
std::remove_if
算法(在
中)适用(与大多数其他算法一样)在语义稍有不同的list类中还有一个
std::list::remove_if
成员函数(
std::remove_,如果
不修改容器,
std::list::remove_if
将从容器中删除元素)@tuxworker我添加了一个例子。@tuxworker如果您在问题中提到这一点,并解释您所做的尝试,这个问题会更好。@ShawnChin我添加了我所做的tried@juanchopanza谢谢你的回答。它对我有效。事实上,我的谓词是正确的,但我没有使用擦除:(
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

struct V
{
    int x; 
    int y;
};

bool y_less_than_5(V const &v)
{
    return v.y < 5;
}


int main()
{
    vector<V> vec;
    V v;
    v.x = 4;  v.y = 1; vec.push_back(v);
    v.x = 17; v.y = 3; vec.push_back(v);
    v.x = 21; v.y = 5; vec.push_back(v);
    v.x = 36; v.y = 7; vec.push_back(v);
    v.x = 25; v.y = 9; vec.push_back(v);

    vec.erase(
        remove_if(vec.begin(), vec.end(), y_less_than_5),
        vec.end());

    for(vector<V>::const_iterator it = vec.begin(); it != vec.end(); ++it)
    {
        cout << "[" << it->x << "," << it->y << "]" << endl;
    }
}
[21,5]
[36,7]
[25,9]
v1.erase( std::remove_if( v1.begin(), v1.end(), [](V const& v) { return v.y<value; }),
          v1.end());