I have a class called 'Graph' which has two unordered maps as private members. I add pairs to these maps and it seems to work fine. But when I try to use the maps inside of a certain function they return 0 for any key that is passed. And when I iterate through the map I see that there are many weird entries that are combinations of various keys I have used.
Here v1 and v2 are strings, and when I print out vMap[v1] and vMap[v2] they print the correct values. But the addEdge() function does not work properly:
void Graph::addEdge(string v1, string v2, int weight) {
if(weight > 0) {
if(eMap.find(v1.append(v2)) == eMap.end()) {
Edge* e = new Edge({v1, v2, weight});
edges.push_back(e);
eMap[v1.append(v2)] = edgeCount;
eMap[v2.append(v1)] = edgeCount;
int first = vMap[v1];
int second = vMap[v2];
matrix[first][second] = weight;
matrix[second][first] = weight;
edgeCount++;
} else {
int i = eMap[v1.append(v2)];
edges[i]->weight = weight;
}
}
}
Here the mapped value of vMap is always 0, I have no idea what is happening. This code was working perfectly earlier and I can't understand what I have done that has messed it up.
Be aware that operator[] as in myMap[myKey] has a double purpose in std::map and std::unordered_map: 1) if myKey doesn't exist, insert it with a value-initialized element (by using the default constructor if it's a class). 2) if myKey does exist, return the element associated with it.
Thanks for the response. This is something I had considered, but even under a controlled input I am having problems. The map is fine and in the condition I would like until addEdge() is called. Once in this function any key which was valid is now mapped to 0.