Lahiru Chandima
Lahiru Chandima

Reputation: 24068

Convert QList<std::string> to QList<QString>

Is there an easy way to create a QList<QString> from QList<std::string>?

(Without iterating QList<std::string> and adding each element to QList<QString>)

Upvotes: 2

Views: 3828

Answers (2)

Miki
Miki

Reputation: 41765

You can't do that without iterating through your list. You can still do it efficiently, avoiding unnecessary copies and reallocations:

QList<std::string> listStd;
listStd << "one" << "two" << "three";

QList<QString> listQt;
listQt.reserve(listStd.length());
for(const std::string& s : listStd)
{
    listQt.append(QString::fromStdString(s));
}

// listQt: "one", "two", "three"

If you don't want to convert, you may want to save your std::string directly as QString, thus avoiding the need to convert later.

QList<QString> lst; // or you can use the typedef QStringList 
....
std::string s = getting_a_std_string_from_this_function();
lst.append(QString::fromStdString(s));

Upvotes: 1

Vedanshu
Vedanshu

Reputation: 2296

The answer is NO. How could you possibly convert one into another without iterating? Even if you are using some kind of functions, that will be iterating through the list.

Upvotes: 1

Related Questions