【问题标题】:Access the variable from for_each in the for_each loop在 for_each 循环中从 for_each 访问变量
【发布时间】:2018-02-23 09:28:20
【问题描述】:

我的代码如下所示:

int multiplyBy2 (int x) {return x*2;}
int add10 (int x) {return x+10;}
int divideBy2 (int x) {return x/2;}

QVector<int> doAnything(QVector<int> list, QVector<std::function<int (int)>> methods){

    for(int i = 0; i< methods.size(); i++){
        std::transform(list.begin(), list.end() , list.begin() ,methods.at(i));
    }
    return list;
}

int main(int argc, char *argv[])
{

    QVector<int> list {1,2,3,4,5};
    QVector<std::function<int (int)>> functions {multiplyBy2 , add10 , divideBy2};

    auto result = doAnything(list, functions);
    std::for_each(result.begin(), result.end(), [](int i){qDebug() << i;});
    return 0;
}

函数 doAnything 对值列表执行函数列表。
此代码运行良好。

现在我已经尝试在 for_each 循环中执行此操作:

std::for_each(methods.begin(), methods.end(),
               std::transform (list.begin(), list.end(), list.begin() , varFromForEach));

我的问题是我不知道如何从 for_each 循环中的 for_each 循环访问变量,例如 Kotlin 中的 it 或 scala 中的 _

任何人都可以帮助我吗?谢谢!

【问题讨论】:

  • 看看std::for_each函数的签名应该等同于:void fun(const Type &amp;a); 签名不需要有const &amp;Type 类型必须使得 InputIt 类型的对象可以被取消引用,然后隐式转换为 Type 在这种情况下,a 是“for_each 循环中的变量”。跨度>

标签: c++11 foreach


【解决方案1】:

您尝试在您的std::for_each 呼叫中呼叫 std::transform

而是创建一个 lambda,捕获 list 并将来自 std::for_eachstd::function 对象)的值作为参数,并在 lambda 中调用 std::transform

std::for_each(methods.begin(), methods.end(),
              [&list](std::function<int(int)>& f)
              {
                  std::transform(list.begin(), list.end(), list.begin(), f);
              });

您当然也可以使用range-based for loop

for (auto& f : methods)
{
    std::transform(list.begin(), list.end(), list.begin(), f);
}

【讨论】:

  • for_each 无论如何都是多余的。它在 C++03 中起到了作用,但在 C++11 之后我认为使用它没有多大意义。
  • 这不是多余的。在许多情况下,它比基于范围的 for 循环更好地服务于提高可读性的目的。尤其是如果您经常使用 STL 算法。
猜你喜欢
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 2021-01-17
  • 2020-11-01
相关资源
最近更新 更多