如何使用指针指向结构的向量?

时间:2012-04-07 07:15:27

标签: c++ pointers struct

struct Edge;

struct Node {
    int id;
    vector<Edge> *edges;
};

struct Edge {
    int id;
    Node* vertex1;
    Node* vertex2;
};

int main(){
    vector<Edge> nodeEdgeList;
    Node* nodePtr = new Node;
    nodePtr->id = vertex;
    nodePtr->edges = nodeEdgeList;
}

由于最后一行,我得到以下编译器错误。

error: cannot convert 'std::vector<Edge, std::allocator<Edge> >' to 'std::vector<Edge, std::allocator<Edge> >*' in assignment

2 个答案:

答案 0 :(得分:3)

您节点类有一个向量*作为您尝试设置非指向指针的成员

此处的错误消息非常明确error: cannot convert 'std::vector<Edge, std::allocator<Edge> >' to 'std::vector<Edge, std::allocator<Edge> >*' in assignment

所以改为:

int main(){
    vector<Edge> *nodeEdgeList = new Vector<Edge>;
    Node* nodePtr = new Node;
    nodePtr->id = vertex;
    nodePtr->edges = nodeEdgeList;
}

int main(){
    vector<Edge> nodeEdgeList;
    Node* nodePtr = new Node;
    nodePtr->id = vertex;
    nodePtr->edges = &nodeEdgeList;
}

答案 1 :(得分:2)

int main(){
    vector<Edge> nodeEdgeList;
    Node* nodePtr = new Node;
    nodePtr->id = vertex;
    nodePtr->edges = &nodeEdgeList; // <-- use & before
}