【问题标题】:push_back for vector in struct not working结构中向量的 push_back 不起作用
【发布时间】:2014-10-28 17:56:54
【问题描述】:

这是我要编译的代码:

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

我不明白问题出在哪里。

【问题讨论】:

  • 您的代码中没有向量。
  • 你的意思是使用std::vector&lt; std::pair&lt;int, float&gt; &gt;

标签: c++ struct stl


【解决方案1】:

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

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

这将允许您将对添加到向量邻居。请注意,pairs 将按值复制到向量中,这就是我假设您无论如何都尝试对 wvertex 局部变量执行的操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 2013-03-28
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多