gpt4 book ai didi

c++ - remove_if 的惯用 C++

转载 作者:可可西里 更新时间:2023-11-01 15:29:44 25 4
gpt4 key购买 nike

我有这门课

class Point2D
{
public:
bool isValid();
// ...
private:
double x_, y_;
};

我有一个 std::vector< Point2D >我想删除无效点,现在我这样做:

bool invalid ( const Point2D& p )
{
return !p.isValid();
}

void f()
{
std::vector< Point2D > points;
// fill points
points.erase( std::remove_if( points.begin(), points.end(), invalid ), points.end() );
// use valid points
}

是否有一种标准的方法(漂亮地)做到这一点,例如不需要“复制”类方法的功能 Point2D::isValid

也许使用 C++11 lambda(我对 lambda 不是很熟悉)?

最佳答案

试试这个:

points.erase(std::remove_if(points.begin(), 
points.end(),
std::not1(std::mem_fun_ref(&Point2D::isValid))),
points.end());

关于c++ - remove_if 的惯用 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6263044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com