采用测试和变异函数的STL算法

Jon*_*Mee 2 c++ algorithm lambda stl c++11

我想要的是这种行为: void change_if( ForwardIterator first, ForwardIterator last, UnaryPredicate test, UnaryOperation op )

使用for循环实现这一目标的最佳方法是什么?还是有一些我还不知道的STL魔法?

Vla*_*cow 7

这可以在不使用boost的情况下完成,但应用标准算法std::for_each 我不建议使用boost来完成这些简单的任务.在项目中包含boost来执行这样一个简单的任务只是一个愚蠢的事.您可以将boost用于此类任务,前提是它已包含在您的项目中.

std::for_each( first, last, []( const T &x ) { if ( test( x ) ) op( x ); } );
Run Code Online (Sandbox Code Playgroud)

或者,如果要更改序列的元素,则可以删除限定符const

std::for_each( first, last, []( T &x ) { if ( test( x ) ) op( x ); } );
Run Code Online (Sandbox Code Playgroud)

有时当使用序列的整个范围时,使用基于语句的范围而不是算法更简单,因为使用具有lambda表达式的算法有时会使代码更不易读

for ( auto &x : sequence )
{
   if ( test( x ) ) op( x );
}
Run Code Online (Sandbox Code Playgroud)

要么

for ( auto &x : sequence )
{
   if ( test( x ) ) x = op( x );
}
Run Code Online (Sandbox Code Playgroud)