迭代器在"find_if"匹配后指向第一个元素,为什么?
iterator is pointing to first element after a "find_if" match, why?
我现在正在自学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()
方法的局部变量。
相关文章:
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- C++ queue.front();为什么不从第一个元素开始呢?
- 指向数组基址的指针而不是指向第一个元素的指针有什么优点?
- 静态堆栈函数不会 1) 输入第一个元素 2)添加新元素时识别旧元素
- 从队列中删除第一个元素C++
- 如果第一个元素包含任何零,则我的程序以不希望的方式运行
- 为什么数组不打印第一个元素?
- 在数组中显示第一个元素用户输入
- 消除集合的第一个元素
- 为什么指向矢量第一个元素的指针会丢失?
- 如何打印出常量字符串的第一个元素?
- 读取数组的第一个元素还是第 4000 个元素更快?
- 如何在数组的一部分中查找特定值的第一个元素
- 对数组进行排序的算法,先是第一个元素,然后是前 2 个元素,然后是前 3 个元素,依此类推
- 访问指向对象指针向量的指针的第一个元素?
- 引用保留向量中的第一个元素
- 指向数组的指针是否应该等于指向其第一个元素的指针?
- 尝试将参数包的第一个元素作为函数调用,并将包的其余部分作为参数传递给它
- 代码是否有效.如果我想显示第一个元素?如果不是,那么 s.begin() 会返回什么?