c++结构错误

C++ struct error

本文关键字:错误 结构 c++      更新时间:2023-10-16
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);
    }
};

我现在一定是犯了严重的错误,因为我不知道出了什么问题。它不喜欢我在节点映射中放置节点的方式

这是因为你有一个类型不匹配,如果你发布编译错误,这将是明显的:

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

你可能想这样做:

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

在这种特殊情况下不起作用,因为Node不是默认可构造的,而map::operator[]需要这样做。无论如何,以下选项都可以工作:

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.