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?

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top