简体   繁体   English

如何在 QVector 中搜索 QString

[英]how to search a QString in QVector

I have been trying search an id a string saved in QVector like this我一直在尝试搜索一个像这样保存在 QVector 中的字符串

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".我曾尝试使用 find 但它对我不起作用,IDE 没有显示任何错误消息,但在调试窗口中,“迭代器显示”的值“不可访问”。

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, ie the element is not being found in the vector.迭代器不可访问,可能意味着迭代器指向向量的末尾,即在向量中找不到元素。

The solution解决方案

The problem is that std::find , searches an exact match, ie it uses the QString::operator == (const char *) (see Comparing strings ).问题在于std::find搜索精确匹配,即它使用QString::operator == (const char *) (请参阅比较字符串)。

You are looking for a string which starts with "2-".您正在寻找“2-”开头的字符串。 Therefore you have to specify a custom equality check, using std::find_if and f.ex.因此,您必须使用std::find_ifstd::find_if指定自定义相等检查。 a lambda function:一个 lambda 函数:

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.请注意,使用std::find_if很慢(对于大型数组),因为它具有O(N)性能。 Using a QHash<int /*id*/, QString /*message*/> structure may improve your lookup performance.使用QHash<int /*id*/, QString /*message*/>结构可以提高您的查找性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM