Question

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?

Was it helpful?

Solution

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

OTHER TIPS

It can be done without intermediate objects, if you are absolutely sure that the two strings contain only Latin characters:

bool latinCompare(const QString& qstr, const std::string& str)
{
  if( qstr.length() != (int)str.size() )
    return false;
  const QChar* qstrData = qstr.data();
  for( int i = 0; i < qstr.length(); ++i ) {
    if( qstrData[i].toLatin1() != str[i] )
      return false;
  }
  return true;
}

Otherwise you should decode the std::string into a QString and compare the two QStrings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top