gpt4 book ai didi

c++ - for_each(for_each())?

转载 作者:行者123 更新时间:2023-11-28 03:04:56 26 4
gpt4 key购买 nike

这行得通,for_each 传递 vector

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 以处理内部 vector 整数

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; }

没有。 (如果我尝试正确的话,也不会使用 bind。)编译器说 def 函数无法应用正确的转换,即从 vector 分配器( vector 的位置指针?)到 const int&,前一个示例通过 vector 分隔函数 f 实现.

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

最佳答案

最简单的解决方案是在 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);
}
}

关于c++ - for_each(for_each())?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19967493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com