Im trying to write a search function to get an element in std::list by suing std:find. But im stuck in the third parameter in the find argorithm, regard to this guy How to search for an element in an stl list? I did overload the operator == pretty much but it seems still not working with the std::find.
This is my code:
class Node
{
string word;
int count;
public:
Node(string _word) :word(_word), count(0) {}
~Node() {}
const string& getWord() const{
return word;
}
bool operator == (const Node& other) const {
return (this->word.compare(other.word) == 0);
}
};
const Node &getNode(const list<Node> &nodes, const string &word){
list<Node>::iterator itr;
itr = find(nodes.begin(), nodes.end(), new Node(word)); <-- no viable overload '='
return *itr;
}
I’m going very crazy with that issue now, please suggest me some hints. Thanks
To get the code working just remove the
newfrom thesortcall. However, this is not going to make your code any better.
You don’t check if the element was actually found and just dereference
the iterator. If the element wasn’t found, this is undefined behavior.
Now, how to fix this.
Nodehas a list, she should be perfectly capable of callingstd::sorthimself.std::stringdue to the single argument constructor taking astring(this should take a string by reference, though). So you can just writestd::find(begin(nodes), end(nodes), "foobar");.operator==(const Node&, const std::string&)andoperator==(const std::string&, const Node&).In any case. Remove
using namespace std;from your headers.