remove_if
不适用于关联容器。但remove_copy_if
可能会起作用,但会以复制地图为代价。相反,我会用count_if
.
1) 使用 bind + less<> 的标准 STL 函数对象和技术,但无需编写自定义函子
// I don't think it can be done with standard c++ without introducing new functors and adaptors.
std::size_t count = std::count_if( m.begin(), m.end(),
std::sgi::compose1(
std::bind_2nd( std::less<int>(), 3 ),
&boost::get<1,mymap::value_type> ) );
2) Boost.Bind
std::size_t count = std::count_if( m.begin(), m.end(),
boost::compose_f_gx(
&boost::bind( std::less<int>, _1, 3 )
&boost::get<1,mymap::value_type> ) );
3) C++0x Lambda
std::size_t count = std::count_if( m.begin(), m.end(),
[]( const mymap::value_type& item )
{ return item.second < 3; } );
如果你真的想要 remove_if 行为,你需要推出自己的算法。我不相信有任何适用于关联容器的修改标准算法。
template< typename FwdIter, typename AssocCont, typename Pred >
std::size_t assoc_remove_if( FwdIter iter, FwdIter end, AssocCont& cont, Pred pred )
{
std::size_t count = 0;
while( iter != end )
{
if( pred(*iter) )
{
++count;
iter = cont.erase(iter);
}
else
{
++iter;
}
}
return count;
}