我有一个容器,它将迭代器存储到其他容器,如下所示:
typedef int my_id; //id
typedef std::set<my_id> my_group_t; //group containing ids
typedef typename my_group_t::iterator my_group_it_t; //group iterator
std::pair < my_group_it_t, my_group_it_t > pair_it_t; //pair (generally begin,end)
typedef std::vector< pair_it_t > my_group_container_t;
my_group_container_t my_group_container; // (FILL the Container and group with some values)
//print the values using lambdas
auto x = my_group_container.begin();
auto y = my_group_container.end();
//x is iterator to the vector, similarly y.
//note that x and y when dereferenced give the pairs of iterators
std::for_each (x, y, [](**xxxx** pair) -> void {
auto xx = x.first; //get first iterator pair
auto yy = x.second; //get second iterator pair
}
配对的类型应该是什么? xxxx
。我知道 lambda 不能在 C++11 中模板化,但我不确定如何在此处使用 decltype
。
//I can do this:
for (; x!=y; ++x) {
auto xx = x->first;
auto yy = x->second;
std::copy(xx,yy,std::ostream_itearator<..> (std::cout, "\n");
}
请注意,虽然示例使用具体类型,但我的实际用例是在模板代码中,其中真实类型未知。
最佳答案
如果您想通用,您有多种选择:
在
x
类型上使用迭代器特征:std::for_each(x, y, [](std::iterator_traits<decltype(x)>::value_type pair) { ... })
使用
*x
的返回类型:std::for_each(x, y, [](decltype(*x) pair) { ... })
使用容器的值类型(直接或推导):
std::for_each(x, y, [](my_group_container_t::value_type pair) { ... }) std::for_each(x, y, [](decltype(my_group_container)::value_type pair) { ... })
如果您确实知道类型(如示例中所示),您当然可以直接使用它:
std::for_each(x, y, [](pair_it_t pair) { ... })
在所有情况下,您都可以根据需要使用 const
和/或 &
修饰 pair
的类型。请注意,在情况 2 中,该类型很可能已经是一个引用 - 需要前向(或更好)运算符来返回实际引用。
关于c++ - 推导 C++11 中 lambda 参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27288633/