【发布时间】: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 在您的两部分布尔表达式中。