我现在在教自己C++,所以我很新。我正在从中学习的书中的一个问题问题是要求比较两个字符串的二元谓词。下面我复制了我写的内容。我确信这是一个非常简单的解决方案,但我无法自己弄清楚。基本上,我的错误是在if语句中。当匹配时,它总是打印出第一个元素,而不是出现匹配的元素。你能解释为什么吗?我究竟做错了什么?另外,作为一个新手,如果您看到任何“难看的代码”,并且能够识别出您将写入不同的内容以便我可以清理它,我会很感激。谢谢!迭代器在“find_if”匹配后指向第一个元素,为什么?
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
//my comparison predicate starts here
struct comparison{
string deststring1;
string deststring2;
comparison (const string& whattheyenter){
deststring1.resize(whattheyenter.size());
transform(whattheyenter.begin(),whattheyenter.end(),deststring1.begin(),tolower);
}
bool operator() (const string& string2) {
deststring2.resize(string2.size());
transform(string2.begin(),string2.end(),deststring2.begin(),tolower);
return (deststring1<deststring2);
}
};
//program begins here
int main(){
string comparethisstring;
cout<<"enter string to compare: "<<endl;
cin>>comparethisstring;
vector<string> listofstrings;
listofstrings.push_back("my fiRst string");
listofstrings.push_back("mY sEcond striNg");
listofstrings.push_back("My ThIrD StRiNg");
auto ielement = find_if(listofstrings.begin(),listofstrings.end(),comparison(comparethisstring));
if (ielement!=listofstrings.end()){
// when there is a match this always prints "my fiRst string" instead of
// pointing to the element where the match is.
cout<<"matched:" <<*ielement;
}
else {
cout<<"no match found!";
}
return 0;
}
编辑:只是想说这个问题是第一次,我用一个比运算符,这是没有用的比较平等。其次,我使用cin而不是getline。因此,当我输入“我的第一个字符串”cin只分配了“我的”来比较字符串。感谢大家的帮助!
''时deststring1
对不起,我不知道我用比运营商更少。这解释它。我想不管来比较两个字符串情况 –
最有可能的,你的意思是使用谓词测试对于“平等”。(不管你定义的意思)。 –