c++qtqstringqvector

how to search a QString in QVector


I have been trying search an id a string saved in QVector like this

QVector<QString> logMessages;
 
logMessages.append("1- Message");
logMessages.append("2- Message");
logMessages.append("3- Message");
logMessages.append("4- Message");  

I have tried to use the find but it didn't work with me, the IDE doesn't show any error messages, but in the debug windwo the value of " iterator display "not accessible".

This is what I have tried so far but, it didn't work with me.

QVector<QString>::iterator it = std::find(logMessages.begin(), logMessages.end(), "2");
if(it != logMessages.end())
{
    int index = std::distance(logMessages.begin(), it);
}

Solution

  • The problem

    The iterator not being accessible, probably means the iterator points to the end of the vector, i.e. the element is not being found in the vector.

    The solution

    The problem is that std::find, searches an exact match, i.e. it uses the QString::operator == (const char *) (see Comparing strings).

    You are looking for a string which starts with "2-". Therefore you have to specify a custom equality check, using std::find_if and f.ex. a lambda function:

    QVector<QString>::iterator it = std::find_if(logMessages.begin(), logMessages.end(), [](const QString& s){
      return s.startsWith("2-"); // check if the element starts with "2-"
    });
    

    Performance consideration

    Note that using std::find_if is slow (for large arrays) as it has O(N) performance. Using a QHash<int /*id*/, QString /*message*/> structure may improve your lookup performance.