在向量初始化中调用对象的非默认构造函数

发布于 2024-10-04 00:53:01 字数 387 浏览 1 评论 0 原文

我想在构造函数的初始化列表中初始化一个向量。该向量由具有参数化构造函数的对象组成。我所拥有的是:

Class::Class() : 
   raster_(std::vector< std::vector<Cell> > (60, std::vector<Cell>(80)))
{
...

如何在上一行中使用两个参数调用 Cell::Cell ?显而易见:

raster_(std::vector< std::vector<Cell(true,true)> > (60, std::vector<Cell(true,true)>(80)))

没有用。

I want to initialize a vector in an initialization list of a constructor. The vector consists of objects with a parameterized constructor. What I have is:

Class::Class() : 
   raster_(std::vector< std::vector<Cell> > (60, std::vector<Cell>(80)))
{
...

How can I call Cell::Cell with two parameters in the above line? The obvious:

raster_(std::vector< std::vector<Cell(true,true)> > (60, std::vector<Cell(true,true)>(80)))

didn't work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枕梦 2024-10-11 00:53:01

您应该尝试:

Class::Class() : 
     raster_(60, std::vector<Cell>(80, Cell(true, true)))
{
    /* ... */
}

请注意,我删除了无用的 std::vector > 来自初始化器。另请注意,根据复制 Cell 的成本,这可能非常无效:

  • 它通过复制提供值的 80 倍来创建 std::vector < code>Cell(true, true)
  • 它创建一个 std::vector > 通过复制提供的向量(本身包含 80 个元素)60 倍!

You should try :

Class::Class() : 
     raster_(60, std::vector<Cell>(80, Cell(true, true)))
{
    /* ... */
}

Note that I removed the useless std::vector<std::vector<Cell> > from the initializer. Also be aware that this could be highly ineffective depending on the cost of copying a Cell :

  • It creates an std::vector<Cell> by copying 80 times the provided value Cell(true, true)
  • It creates an std::vector<std::vector<Cell> > by copying 60 times the provided vector (which contains 80 elements itself) !
甜点 2024-10-11 00:53:01

:raster_(std::vector< std::vector > (60, std::vector(80, Cell(true, true))));

如果 raster_ 是接受向量的东西。如果 raster_ 本身是向量,则像这样

:raster(60, std::vector(80, Cell(true, true)))

:raster_(std::vector< std::vector<Cell> > (60, std::vector<Cell>(80, Cell(true, true))));

if raster_ is something that takes the vector. If raster_ itself is the vector then like this

:raster(60, std::vector<Cell>(80, Cell(true, true)))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文