【问题标题】:Comparing two string iterators always comes out true C++比较两个字符串迭代器总能得出真正的 C++
【发布时间】:2015-05-17 02:11:05
【问题描述】:

所以,这里有一个奇怪的问题,我真的只是遇到了麻烦。我有一个字符串列表,我正在尝试查看其中两个是否匹配。所以,我有一个遍历并获取每个字符串,另一个检查它是否匹配。但是,它总是说这两个是真的 - 即使第一个在列表中没有匹配项。

for(iterator = tagList.begin(); iterator != tagList.end(); ++iterator)
{
  string theWord = *iterator;
  string currentWord = *iterator;
  if(currentWord[0] == '<' && currentWord[1] != '/')
  {
     bool matchFound = false;

     list<string>::const_iterator it2;
     for(it2 = (++iterator); it2 != tagList.end(); ++it2)
     {
        string temp = *it2;
        if(currentWord.compare(temp) && temp != "")
        {
           fixedString += theWord + ' ';
           matchFound = true;

           cout << "A match was found... Current string: " 
                << fixedString << endl;
           cout << "\tthe matched word was " << *it2 << endl;
           break;
        }
     }
     if(!matchFound)
     {
        currentWord = *iterator;
        currentWord = currentWord.substr(1, currentWord.size() - 2);
        fixedString += currentWord;
        cout << "No match was found... Current string: " << fixedString 
             << endl;
     }
  }
}

关于为什么它总是正确的任何想法?

【问题讨论】:

  • currentWord.compare(temp) 等同于currentWord != temp - 与您所说的相反。阅读精品手册,描述string::compare返回值的部分。
  • 在修复该问题时,temp != "" ==> !temp.empty(),您可能希望 first 在您的两部分布尔表达式中。

标签: c++ string iterator


【解决方案1】:

您的问题在于currentWord.compare(temp)string::compare() 的返回类型为 int,如果它们相等,则返回类型为 0(计算结果为 false),如果它们不同(计算结果为 true),则返回正或负数值。

你想要:

if((currentWord.compare(temp) == 0) && temp != "") {
...

您可以在此处阅读有关string::compare() 的信息: http://www.cplusplus.com/reference/string/string/compare/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    相关资源
    最近更新 更多