简体   繁体   English

转换QList <std::string> 到QList <QString>

[英]Convert QList<std::string> to QList<QString>

Is there an easy way to create a QList<QString> from QList<std::string> ? 有没有一种简单的方法可以从QList<std::string>创建QList<QString> QList<std::string>

(Without iterating QList<std::string> and adding each element to QList<QString> ) (无需迭代QList<std::string>并将每个元素添加到QList<QString>

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. 即使您使用某种功能,也要遍历列表。

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. 如果您不想进行转换,则可以将std::string直接保存为QString ,从而避免以后进行转换。

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));

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

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