I have a const-correctness problem which I don't seem to be able to resolve. Here is the structure of my program:
class Node
{
private:
int id;
std::set<Node*> neighbours;
public:
Node();
Node(int id_p);
void set_id(const int& id_p);
int get_id() const;
void add_neighbour(Node* neighbour);
bool is_neighbour(Node* neighbour) const;
friend bool operator <(const Node& lhs, const Node& rhs);
};
class Graph
{
private:
std::set<Node> node_list;
public:
Graph();
void add_node(int id);
const Node* get_node_by_id(int id) const;
bool has_node(int id) const;
void check_add_node(int id);
void add_edge(int id_1, int id_2);
bool has_edge(int id_1, int id_2) const;
void check_add_edge(int id_1, int id_2);
(...)
};
Now the thing is, if I call the function Graph::get_node_by_id()
, I want to return a pointer to a given node (type Node
). But it seems impossible to do so, because the std::set
implicitly converts my Node type objects to const Node
objects, and I am unable fetch a non-const pointer
from a const
object.
However, I cannot have everything else set to const Node
(which would resolve the problem), because I want to call Node::add_neighbour()
from Graph::add_edge()
, but whenever I do so, my compiler says that I might be violating the const
ness (required to have a sorted set) of the elements in the node_list
set, even though I defined the less operator<
to only care about the id
.
Is there anything I can do to resolve this dilemma (without giving up on having a sorted set)? Thank you for your responses!
More info on the error:
If I use non-constant fields, error in Graph::get_node_by_id()
:
for(Node& element : this->node_list) // Error: element should be const Node&
{
if(element->get_id() == id)
{
return element;
}
}
return nullptr;
If I use constant fields, error in Graph::add_edge()
:
(...)
const Node* node_1 = this->get_node_by_id(id_1);
const Node* node_2 = this->get_node_by_id(id_2);
node_1->add_neighbour(node_2); // Error for disregarding constness
node_2->add_neighbour(node_1);