Search code examples
c++qtqstringqtcoreqvector

Access QVector element index by its content


I have a QVector of QStrings and I want to remove element with its content, but I don't know how to find index of it. Do you know how can I remove it? I don't want to iterate over it and compare its content by my value.

My QVector is declared as follows:

QVector <QString> user_valid;

and I want to remove it by its content, for example element with value "marigold":

user_valid.remove(user_valid.find("marigold");

Thank you in advance!


Solution

  • OK, so I would do the following if I were you:

    • Use QStringList instead of QVector<QString> as it has convenience methods that can be useful for you; it is also more common and hence comprehensive. You would spare one extra method call even in this case.

    • Just use the removeOne() and/or removeAll() methods depending on your exact scenario.

    Therefore, I would be writing something like this:

    QStringList user_valid;
    user_valid << "marigold" << "cloud" << "sun" << "rain";
    user_valid.removeOne("marigold");
    // user_valid: ["cloud", ,"sun", "rain"]
    

    If you really insist on using QVector<QString> - which is a bad idea in my opinion -, you would need to get the index first by the indexOf() method, so you would be writing this:

    user_valid.remove(user_valid.indexOf("marigold"));