[英]Idiomatic C++ for remove_if
我有這個 class
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
}
是否有這樣做的標准方法(漂亮),例如不需要“復制” class 方法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());
不完全標准,但幾乎:您可以使用 boost::bind 並執行以下操作
points.erase( std::remove_if( points.begin(), points.end(),
!boost::bind(&Point2D::isValid, _1 )), points.end() );
順便說一句,您應該聲明 isValid 方法 const。
lambda 版本也不會更干凈,但它還有另一個重要優勢:局部性。 您會看到使用它的代碼:
points.erase( std::remove_if( points.begin(), points.end(),
[](const Point2D& p){
return !p.isValid();
}), points.end() );
請注意,您需要更改isValid
以使其成為const
function,否則您不能在引用 const ( const Point2D&
) 時調用它。
另一種選擇是實施operator!
對於您的 class:
class Point2D{
// ... as before
public:
bool isValid() const;
bool operator!() const{
return !isValid();
}
};
請注意,這兩個函數都是 const。 現在你可以實現一個通用的否定函子:
struct negate{
template<class T>
bool operator()(T const& t){
return !t;
}
};
並使用它:
points.erase( std::remove_if( points.begin(), points.end(), negate()), points.end() );
你可以使用std::mem_fun_ref
和std::not1
的組合來做你想做的事:
points.erase( std::remove_if( points.begin(), points.end(),
std::not1( std::mem_fun_ref( &Point2D::isValid ) ) ),
points.end() );
對於它的價值,唯一的“慣用”部分是erase-remove idiom 。
如果 Boost 適合您,請將 @Randall Flagg 建議的內容與boost::remove_erase_if
一起使用:
boost::remove_erase_if(points, !boost::bind(&Point2D::isValid, _1));
我想你正在尋找not1
編輯:仔細看看你的例子,我認為你不能以任何其他方式做到這一點,因為isValid()
是 function 的成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.