vendredi 23 février 2018

Access the variable from for_each in the for_each loop

I have Code that looks like this:

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

The function doAnything performs a list of functions on a list of values.
This code works fine.

Now I have tried, to do this in a for_each loop:

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

My problem is that I doesn't know how to access the variable from the for_each loop in the for_each loop like it in Kotlin or _ in scala

Can anyone help me please? Thanks!

Aucun commentaire:

Enregistrer un commentaire