动态分配到2维std :: unordered_map

时间:2016-08-15 22:41:05

标签: c++ dictionary

我有一张声明为

的二维地图
    unordered_map< string, unordered_map<string, Road*>* > matrix;

这需要一个道路实例

class Road {
public:
    Road() : connected(0), weight(0) {}

    bool connected;
    int weight;
};

我分配如下

void addPlace(string place) {
    // error checking
    if (placeExists(place)) {
        cout << "Place already exists" << endl;
        return;
    }

    Road *road = new Road();
    unordered_map<string, Road*> *newRelationship = new unordered_map<string, Road*>;
    newRelationship->insert({ {place},{road} });

    // add to network
    matrix.insert({ { place },{ newRelationship } });
    ++n_verticies;
}

然而,当我打电话

void connectPlace(string source, string dest, int w)
    if (!placeExists(dest) || !placeExists(source)) {
        cout << "Place(s) does not exists" << endl;
        return;
    }
     ...
     if (matrix.find(source)->second->find(dest)->second->connected)

我收到一个错误:“列表迭代器不能解除引用”,这告诉我,我的分配错了?提前谢谢。

这是我对placeExists的调用,它返回true来自connectPlace的两个调用:

bool placeExists(string place) {
    if (matrix.find(place) == matrix.end()) {
        return false;
    }
    return true;
}

我把它分解为

    auto a = matrix.find(source);
    auto b = matrix.find(source)->second;
    auto c = matrix.find(source)->second->find(dest); // (<Error reading characters of string.>, {connected=??? weight=??? })
    auto d = matrix.find(source)->second->find(dest)->second; // stops here
    auto e = matrix.find(source)->second->find(dest)->second->connected;

我的函数调用如下

Graph *road_network = new Graph(false);

road_network->addPlace("Sacremento");
road_network->addPlace("Antelope");
road_network->addPlace("Roseville");
road_network->addPlace("San Francisco");
road_network->addPlace("San Jose");
road_network->addPlace("Davis");
road_network->addPlace("Los Angelous");

road_network->connectPlace("Sacremento", "Antelope", 5); //<-- break
road_network->connectPlace("San Francisco", "San Jose", 2);
road_network->connectPlace("Los Angelous", "Davis", 10);
road_network->connectPlace("Davis", "Antelope", 4);
road_network->connectPlace("Roseville", "Davis", 5);
road_network->connectPlace("San Jose", "Antelope", 6);
road_network->connectPlace("Davis", "Los Angelous", 5);

1 个答案:

答案 0 :(得分:3)

问题的一个主要原因是你试图在一行代码中做太多。

if (matrix.find(source)->second->find(dest)->second->connected)

这应该分为几行。具体来说,您需要确保在继续之前对find()的任何调用都成功:

auto found = matrix.find(source);
if (found != matrix.end()) {
    // keep going
}
else {
    // print error message
}

就个人而言,我更喜欢这种解决方案,而不是重构placeExists(),原因有两个:

  1. 这可以避免多次调用find()
  2. 这明确显示了每个数据结构的每次访问。
  3. 它避免假设当matrix中存在密钥时,它也存在于嵌套unordered_map中。