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);
}
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 theQString::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_ifand f.ex. a lambda function:Performance consideration
Note that using
std::find_ifis slow (for large arrays) as it hasO(N)performance. Using aQHash<int /*id*/, QString /*message*/>structure may improve your lookup performance.