升压转换迭代器和C ++ 11的lambda [英] boost transform iterator and c++11 lambda
本文介绍了升压转换迭代器和C ++ 11的lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用boost ::适配器::通过向适配器提供的C ++ 0x的lambda转变。
I'm trying to use boost::adaptors::transformed by providing a c++0x lambda to the adaptor.
以下code不能编译。我使用的是G ++ 4.6.2提升1.48。
The following code does not compile. I'm using g++ 4.6.2 with boost 1.48.
#include <iostream>
#include <vector>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
using namespace std;
namespace br = boost::range;
namespace badpt = boost::adaptors;
int main()
{
vector<int> a = {0,3,1,};
vector<int> b = {100,200,300,400};
auto my_ftor = [&b](int r)->int{return b[r];};
cout<<*br::max_element(a|badpt::transformed(my_ftor))<<endl;
}
这是我做错了什么在这里的任何想法?
Any ideas on what I'm doing wrong here?
推荐答案
好lambda表达式没有发挥好,因为它们没有缺省构造,这是必要的迭代器。这是一个包装我使用的lambda表达式:
Well lambdas don't play nice, since they are not default constructible, which is necessary for iterators. Here is a wrapper I use for lambdas:
#define RETURNS(...) -> decltype(__VA_ARGS__) { return (__VA_ARGS__); }
template<class Fun>
struct function_object
{
boost::optional<Fun> f;
function_object()
{}
function_object(Fun f): f(f)
{}
function_object(const function_object & rhs) : f(rhs.f)
{}
// Assignment operator is just a copy construction, which does not provide
// the strong exception guarantee.
function_object& operator=(const function_object& rhs)
{
if (this != &rhs)
{
this->~function_object();
new (this) function_object(rhs);
}
return *this;
}
template<class F>
struct result
{};
template<class F, class T>
struct result<F(T)>
{
typedef decltype(std::declval<Fun>()(std::declval<T>())) type;
};
template<class T>
auto operator()(T && x) const RETURNS((*f)(std::forward<T>(x)))
template<class T>
auto operator()(T && x) RETURNS((*f)(std::forward<T>(x)))
};
template<class F>
function_object<F> make_function_object(F f)
{
return function_object<F>(f);
}
然后,你可以这样做:
Then you can just do this:
int main()
{
vector<int> a = {0,3,1,};
vector<int> b = {100,200,300,400};
cout<<*br::max_element(a|badpt::transformed(make_function_object([&b](int r)->int{return b[r];};)))<<endl;
}
这篇关于升压转换迭代器和C ++ 11的lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文