class Node{
public:
Node* back1 = nullptr;
Node* back2 = nullptr;
int value;
Node(int value) {
this->value = value;
}
//bool operator< (const Node& rhs) const {return this->value < rhs.value;}
bool operator< (const Node* rhs) const {return this->value < rhs->value;}
};
std::unordered_map<int, std::set<Node*>> nodes;
void subtractOneOrDouble(int current, int m, Node& prevNode) {
if (current != 0 && current < m && nodes[current % 10].find(current) == nodes[current % 10].end()) {
I have a set of Nodes* and not only do I want to sort them by the value of each node, I want to use find(), input a value, and get the pointer to the node that corresponds to that value. From what I think is going on, find() is taking in pointers, not actual values. What would I need to change so that find() takes in an integer value and gives me the pointer to the Node with that value?
CodePudding user response:
The problem is with the expression
nodes[current % 10].find(current)
The index operator []
of the std::unordered_map
will return a std::set
(the value of the hash map). Then you apply the find
function of the std::set
. This set contains "Node*"s. But you are trying to find an int
(current). This cannot work.
I am not sure what exactly you want to achieve, but your are searching with the wrong type. You need to give a const Node*
as aparameter to the find function.
CodePudding user response:
find
takes as input the key type. In your std::unordered_map
, that key type is int
, and in your std::set
that key type is Node*
.
If you want to use your elements' sorting, then you can change your std::set
's key to be Node
instead of Node*
. std::set
's comparison uses operator <
(via std::less
) by default, so you can get this working with some tweaks to your code. Here's an example that shows how finding by value can work:
#include <iostream>
#include <set>
struct Node {
int value;
Node(int v):value(v) {}
bool operator <(const Node& rhs) const {
return value < rhs.value;
}
};
int main() {
std::set<Node> nodes;
nodes.emplace(1);
nodes.emplace(2);
nodes.emplace(3);
auto found = nodes.find(Node(2));
if (found != nodes.end()) {
std::cout << "Found node " << found->value << std::endl;
}
else {
std::cout << "Didn't find node!" << std::endl;
}
return 0;
}
This prints:
Found node 2
As it is in your question, your std::set
will be sorted by memory address (because that's how Node*
is sorted), and not by Node::value
.