Join list returned from QtConcurrent::map into a single list



  • I was wondering how to join multiple lists (QStringList) returned by QtConcurrent::map into a single list?

    QStringList magic(const QString &name)
    {
        return { name.toLower(), name.toUpper() };
    }
    
    QStringList names = { "john", "jane" };
    QFuture<QStringList> example = QtConcurrent::mapped(names, magic);
    

    In example.results() I will get (("john", "JOHN"), ("jane", "JANE")), I want to reduce it to ("john", "JOHN", "jane", "JANE") in a single QStringList.



  • you can either merge them afterwards:

    QStringList finalRes;
    const auto interRes = example.results();
    for(auto i=interRes.constBegin();i!=interRes.constEnd();++i)
    finalRes.append(*i);
    

    or use mappedReduced



  • I tried to use mappedReduced as it seems to be the more appropriated way, but it doesn't work as I expected.

    The first thing I noticed is that the reduce method can't be a lambda, and...

    void reduce(QStringList &result, const QStringList &names)
    {
        // ...
    }
    

    And the second thing is that mappedReduced will call reduce twice and I don't know how to merge from here...

    I don't know where to go now...



  • @Defohin said in Join list returned from QtConcurrent::map into a single list:

    The first thing I noticed is that the reduce method can't be a lambda

    Not really, you just need to explicitly set the template parameter.

    @Defohin said in Join list returned from QtConcurrent::map into a single list:

    And the second thing is that mappedReduced will call reduce twice

    yes, 2 elements in the list = 2 calls.

    using your example and a lambda:

    QFuture<QStringList> example = QtConcurrent::mappedReduced<QStringList /*this has to be explicitly set to the same type as the first argument in the reduce lambda*/>(
    names
    , magic
    , [](QStringList& redu,const QStringList& val)->void{redu.append(val);}
    , QtConcurrent::OrderedReduce // ensures the order is the same as the input
    );
    


  • Oh gosh, you are amazing, thank you.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.