结构中矢量的push_back不起作用

push_back for vector in struct not working

本文关键字:back 不起作用 push 结构      更新时间:2023-10-16

以下是我试图编译的代码:

int main(){
    struct node{
        pair<int, float>* neighbors;
    };
    pair<int, float> wvertex;
    int VCount, v1, v2;
    float w;
    cin >> VCount;
    node* graph_nodes[VCount+1];
    while( cin >> v1 ){
        cin >> v2 >> w;
        wvertex.first = v2;
        wvertex.second = w;
        graph_nodes[v1]->neighbors.push_back(wvertex);
    }
    return 0;
}

但是,它在编译时给出了一个错误:

In function ‘int main()’:
error: request for member ‘push_back’ in ‘graph_nodes[v1]->main()::node::neighbors’, which is of non-class type ‘std::pair<int, float>*’

我不明白问题出在哪里。

将结构定义更改为以下内容:

struct node{
    vector< pair<int, float> > neighbors;
};

这将允许您向向量邻居添加对。注意,对将按值复制到向量中,我假设您无论如何都在尝试使用wvertex局部变量。