Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficiently compare QString and std::string for equality

I want to efficiently compare a QString and a std::string for (in)equality. Which is the best way to do it, possibly without creating intermediate objects?

like image 850
Ber Avatar asked Aug 14 '13 10:08

Ber


1 Answers

QString::fromStdString() and QString::toStdString() comes to mind, but they create temporary copy of the string, so afaik, if you don't want to have temporary objects, you will have to write this function yourself (though what is more efficient is a question).

Example:

    QString string="string";
    std::string stdstring="string";
    qDebug()<< (string.toStdString()==stdstring); // true


    QString string="string";
    std::string stdstring="std string";
    qDebug()<< (str==QString::fromStdString(stdstring)); // false

By the way in qt5, QString::toStdString() now uses QString::toUtf8() to perform the conversion, so the Unicode properties of the string will not be lost (qt-project.org/doc/qt-5.0/qtcore/qstring.html#toStdString

like image 55
Shf Avatar answered Nov 10 '22 06:11

Shf