AK_*_*AK_ 1 c++ algorithm boost
我想做一些像c#linq风格的东西:
SomeColection <SomeType> someColection;
someColection.Remove(something => something > 2);
Run Code Online (Sandbox Code Playgroud)
并且它将删除所有大于2(或任何其他布尔条件)的东西......
在项目中使用boost ...
你不需要提升(除非你的主要焦点是内联匿名功能).纯STL很好.
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
int main () {
std::vector<int> x (24);
for (int i = 0; i < x.size(); ++ i)
x[i] = i % 5;
std::vector<int>::iterator
new_end = std::remove_if(x.begin(), x.end(),
std::bind2nd(std::greater<int>(), 2));
x.erase(new_end, x.end());
for (int i = 0; i < x.size(); ++ i)
std::cout << x[i] << " ";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用boost可以替换bind2nd的东西
#include <boost/lambda/lambda.hpp>
...
using boost::lambda::_1;
std::vector<int>::iterator new_end = std::remove_if(x.begin(), x.end(), _1 > 2);
Run Code Online (Sandbox Code Playgroud)
C++ 0x(使用lambdas):
container.erase( std::remove_if( container.begin(), container.end(),
[]( int v ) { return v > 2; } ),
container.end() );
Run Code Online (Sandbox Code Playgroud)
erase与之结合的原因remove_if是STL算法适用于迭代器,而不适用于容器.他们重新定位容器的内容,但他们不会修改容器本身.
C++ 03:
container.erase( std::remove_if( container.begin(), container.end(),
std::bind2nd( std::greater<int>(), 2 ) ),
container.end() );
Run Code Online (Sandbox Code Playgroud)
这可能看起来有点简单,但它也不太灵活,因为已经定义了很多谓词.对于更复杂的操作,您必须编写自己的谓词仿函数.