I have the following map in C++ (gcc):
map<int, EdgeExtended> myMap;
where the definition of EdgeExtended is:
struct EdgeExtended {
int neighborNodeId;
int weight;
int arrayPointer;
bool isCrossEdge;
EdgeExtended(Edge _edge, int _arrayPointer) {
neighborNodeId = _edge.neighborNodeId;
weight = _edge.weight;
arrayPointer = arrayPointer;
isCrossEdge = _edge.isCrossEdge;
}
EdgeExtended(const EdgeExtended & _edge) {
neighborNodeId = _edge.neighborNodeId;
weight = _edge.weight;
arrayPointer = _edge.arrayPointer;
isCrossEdge = _edge.isCrossEdge;
}
EdgeExtended(int _neighborNodeId, int _weight, bool _isCrossEdge, int _arrayPointer) {
neighborNodeId = _neighborNodeId;
weight = _weight;
arrayPointer = _arrayPointer;
isCrossEdge = _isCrossEdge;
}
void setValues(int _neighborNodeId, int _weight, bool _isCrossEdge, int _arrayPointer) {
neighborNodeId = _neighborNodeId;
weight = _weight;
arrayPointer = _arrayPointer;
isCrossEdge = _isCrossEdge;
}
EdgeExtended() {
neighborNodeId = -1;
weight = -1;
arrayPointer = -1;
isCrossEdge = false;
}
};
I want to do this (plain example):
EdgeMap edge;
int nodeId=18;
edge=map.erase(nodeId);
a) Is this code correct, does erase return the object that corresponds to the key? b) If yes, what does erase return when the key is not present? c) if this code is wrong, how can I check if a key is present, the object mapped to the key and then erase the pair from map. Keep in mind that performance is rather crucial, so I need the most efficient way.
a) No, it is not correct. The std::map::erase method you call returns the number of erased elements.
What you can do is use std::map::find to check if the an element with the given key is in the map. This returns an iterator to the element if it exists, to
end()if it doesn’t. You can pass this iterator to the relevantstd::map::eraseoverload.