【问题标题】:How to push_back() a member variable of a struct如何 push_back() 结构的成员变量
【发布时间】:2021-08-22 03:52:19
【问题描述】:

我有一个结构

struct Node
{
    string Name;
    vector<float> probs;
    vector<Node*> connections;
};

我有一个名为 Input 的字符串 vector 每行如下

0 0 1 0 0
0 0 1 0 0
0 0 0 1 1
0 0 0 0 0
0 0 0 0 0

如果我找到 1,我想将 .push_back() 转换为 connections

我用了以下

  int N=5;
  Node Tables[N];

  for (int i = 0; i < N*2-1; ++i)
  {
    for (int j = 0; j < N*2-1; ++j)
    {
      if (Input[i][j] == '1')
      {
        Tables[i].connections.push_back(Tables[j]);
      }
    }
  }

编译时出现此错误

main.cpp:128:31: error: no matching member function for call to 'push_back'
        Tables[i].connections.push_back(Tables[j]);
        ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~

【问题讨论】:

  • connectionspointersNode 的向量,而 Tables[j]Node object(而不是指针)。
  • 是的,我知道我需要Tables[i].connections.push_back(&amp;Tables[j]);
  • 旁白:i &lt; N*2-1 是一个非常可疑的循环边界
  • 是的@Caleth 导致了一个问题,我通过去掉向量中的所有空格来解决它,所以它是一个 5x5

标签: c++ variables vector struct


【解决方案1】:

在结构的声明中,您在该结构内声明了一个节点(指针)向量。 作为一个指针向量,你只能 push_back() 任何 Node 类型的元素 address。 如果您只修改代码如下:Tables[i].connections.push_back(&amp;Tables[j]); 您可以解决该错误。

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多