DoubleBass
DoubleBass

Reputation: 1173

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.

Upvotes: 0

Views: 63

Answers (1)

Barry
Barry

Reputation: 304122

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.

Upvotes: 3

Related Questions