繁体   English   中英

在 C++ 中的结构中分配数组

[英]Allocating an array in a struct in C++

我正在尝试在结构中分配一个结构数组。 这是我的代码:

struct t_nd {
  double stuff;
};

struct t_nwork {
  struct t_nd *nds;
};

struct t_nwork net;

// need to allocate the nds array to be of size 10

试过这个但失败了:

t_nd* net.nds = new t_nd[10];

有人说试试向量,所以我试了:

vector<t_node> net.nodes(10);

但又一次惨败。

有人说尝试向量,所以我尝试了:...但失败了

您可以使用矢量,如下所示。 在所示程序中,我们有一个名为nds的数据成员,类型为vector<t_nd> 此外,我们有一个构造函数,其参数类型为std::size_t

struct t_nd {
  double stuff;
};
struct t_nwork {
  //data member of type std::vector<t_nd>
  std::vector<t_nd> nds;
  
  //constructor to set size of vector 
  t_nwork(std::size_t psize): nds(psize)
  {
      
  }
};


int main()
{
    //create object of type t_nwork whose nds have size 10
    t_nwork net(10);
}

工作演示

方法二

这里我们没有任何构造函数来设置向量的大小。

struct t_nd {
  double stuff;
};

struct t_nwork {
  //data member of type std::vector<t_nd>
  std::vector<t_nd> nds;
  
};

//create object of type t_nwork whose nds have size 10
t_nwork net{std::vector<t_nd>(10)};

演示

这是解决方案:

#include <iostream>

struct t_nd {
    double stuff;
};

struct t_nwork {
    t_nd* nds;
};

int main() {
    t_nwork net;
    net.nds = new t_nd[100];
    // ...
    delete[] net.nds;
}

这是使用向量的解决方案:

#include <iostream>
#include <vector>

struct t_nd {
    double stuff;
};

struct t_nwork {
    std::vector<t_nd> nds;
};

int main() {
    t_nwork net;
    net.nds.resize(10);
    net.nds[1];
}
#include <iostream>
struct xyz {
    int val;
};

struct abc {
    struct xyz *xyzPtr;
};

int main() {
    struct abc myAbc;
    myAbc.xyzPtr = new xyz[10];
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM