1

これは基本的なポインターの質問ですが、これはしばらくの間私を困惑させています。map次のように、基になるデータ構造としてC++ を使用して、重み付きグラフを実装しました。

std::map<int, std::vector<Edge> > edgeList;

このマップは、ノード ID (an ) をキーとして保持し、 a を値としてint使用して、このノードのエッジのリストを保持します。vector

次のように、各ノードのエッジ リストを初期化しました。

for(int i = 0; i< n; i++){
        std::vector<Edge> vi;
        edgeList.insert(std::make_pair(i,vi)); // initialize with empty vector (at least, that's the intent)
    }

vectorここで、グラフにエッジを追加しながら、次のように各ノードに対応するエッジ リストを取得しようとすると、次のようになります。

std::vector<Edge> vList = edgeList.at(v); // v is the node id here

vector以前にその vList にエッジを追加したにもかかわらず、空のvList が返されます。

一方で、

std::vector<Edge> &vList = edgeList.at(v);

私の目的のためにうまくいっているようです。最初の実装が機能せず、2 番目の実装が機能する理由を誰か説明してもらえますか?

編集:グラフにエッジを追加するためのコードは次のとおりです。

void Graph::addEdge(Edge e){

    // retrieve start and end node for this edge
    int v = e.either(); // returns either end of the edge
    int w = e.other(v);

    // retrieve edge lists for these nodes
    std::vector<Edge> vList = edgeList.at(v); // doesn't work
    std::vector<Edge> wList = edgeList.at(w); // doesn't work

    // add this edge to the list of edges
    vList.push_back(e);
    wList.push_back(e);
}
4

2 に答える 2