迭代器在"find_if"匹配后指向第一个元素,为什么?

iterator is pointing to first element after a "find_if" match, why?

本文关键字:第一个 元素 为什么 find if 迭代器      更新时间:2023-10-16

我现在正在自学c++,所以我很新。我正在学习的书中的问题之一是要求一个比较 2 个字符串的二进制谓词。下面我复制了我写的内容。我确信这是那些非常简单的解决方案之一,但我自己无法弄清楚。基本上,我的错误在于 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 只分配了"my"来比较这个字符串。感谢大家的帮助!

find_if查找预测true的第一个元素。 你的预测是"按字母顺序,它是否比comparethisstring早。 您可能希望返回 true 当且仅当您等于 comparethisstring(或 deststring1==deststring2 )。

我还建议deststring2成为operator()方法的局部变量。