push_back for struct in struct not working

时间:2014-09-04 05:17:48

标签: c++ struct stl

以下是我要编译的代码:

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>*’

我无法理解问题所在。

1 个答案:

答案 0 :(得分:2)

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

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

这将允许您将对添加到向量邻居。请注意,对将按值复制到向量中,这是我假设您尝试使用wvertex局部变量进行的操作。