3

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

4

1 回答 1

1

find_if找到预测为 的第一个元素true。您的预测是“它是否早于字母顺序。当且仅当您等于(或)时,comparethisstring您可能希望返回 true 。comparethisstringdeststring1==deststring2

我还建议deststring2为该operator()方法创建一个本地变量。

于 2012-12-18T00:53:43.343 回答