qBinaryFind for QStringList



  • I have 2 QStringLists (L1 is a subset of L2). I need to find the index of all L1 elements in L2. I am using binary search to do the same but I am not sure how to find the index. Also, please do suggest if there is a better way for doing the same.

    Thanks.

     for(int i=0;i<filesGeotagged.length();i++){
    
            QList<QString>::iterator k = qBinaryFind(L2.begin(),L2.end(),L1[i]);
            qDebug() << *k;
    
        }
    

  • Qt Champions 2016

    Hi
    Not tested with Qt but
    Can you do

    int index=(k - L2.begin());
    ?

    You could also use a map, if each L1 element has a good key.
    Then it would be direct lookup.


  • Qt Champions 2016

    Your approach is sound. The only drawback is you'd need to sort L2 (before starting the search) for obvious reasons. Another thing you can try if your lists are long is to hash L2. For example:

    // Preparation part:
    QHash<QString, int> indices;
    indices.reserve(L2.size());
    for (qint32 i = 0, size = L2.size(); i < size; i++)
        indices.insert(L2.at(i), i);
    
    // Search part:
    for (qint32 i=0, size = filesGeotagged.length(); i < size; i++)  {
        qDebug() << indices.value(L1.at(i), -1); // Output the index, handle -1 as an error (i.e. put an assertion)
    }
    


  • @mrjj

    It works !! Thanks.


Log in to reply
 

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