for_each(for_each())?

时间:2013-11-14 00:51:41

标签: c++ c++11 vector foreach

这有效,for_each传递矢量

std::vector<int> v(10, 1);
std::vector< std::vector<int> > vv(10, v);
auto vvit = vv.begin();

std::for_each(vvit, vv.end(), f);

到函数f,它适用于for_each重新使用内部向量整数

void f(const std::vector<int>& v) {std::for_each(v.begin(), v.end(), def);}

但for_each

中的for_each
std::for_each(vvit, vv.end(), std::for_each((*vvit).begin(), (*vvit).end(), def));

和仅用于整理的功能

void def(const int& i) { std::cout << i; }

没有。 (如果我正确尝试的话,也没有绑定。)编译器说def函数不能应用正确的转换,即从向量分配器(向量的位置指针?)到const int&amp ;,这是前一个例子用向量分离函数实现的东西F。

这是复杂还是微不足道的?

1 个答案:

答案 0 :(得分:2)

最简单的解决方案是在lambda中传递for_each

std::for_each(vvit, vv.end(), [f](std::vector<int> const& v)
  { std::for_each(v.begin(), v.end(), f); } );

出了什么问题
for (auto const& v : vv) {
  for (int i : v) {
    f(i);
  }
}