简体   繁体   中英

C++ struct error

struct Node{
    int ID, power, parent;
    vector<int> connectedNodes;

    Node(int ID_arg, int power_arg){
        ID = ID_arg;
        power = power_arg;
        parent = -1;
    }
};

struct Graph{
    int rootID;
    map<int, Node> nodes;
    map<int,int> subtreeSizes;

    Graph(){
        rootID = 1;
        nodes[1] = new Node(1,0);
    }

};

I must be having a serious lapse right now because I have no idea what's wrong. It isn't liking the way I am putting the node in the node map.

That's because you have a type mismatch, which, if you posted the compile error, would be obvious:

nodes[1] = new Node(1,0);
^^^^^^^^   ^^^^^^^^^^^^^
  Node&       Node*

You probably want to do something like:

nodes[1] = Node(1, 0);

That won't work in this particular case since Node isn't default-constructible and map::operator[] requires this. The following alternatives will work regardless:

nodes.insert(std::make_pair(1, Node(1, 0));
nodes.emplace(std::piecewise_construct,
              std::forward_as_tuple(1),
              std::forward_as_tuple(1, 0));
// etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM