【问题标题】:How to set the size of a vector member of a struct upon intialization?如何在初始化时设置结构的向量成员的大小?
【发布时间】:2020-12-04 18:05:53
【问题描述】:

我想在构造struct 时设置成员向量的大小。原因是我发现resize() 可能很慢。

这里有一些最小的代码试图做我想做的事,但是坏了。

#include <iostream>
#include <vector>

using namespace std;

struct Struct_w_Vector {
    ~Struct_w_Vector() {} // destructor

    int n;
    vector<double> h(n, 0.0);

    Struct_w_Vector(int n) : n(n) {
        // create vector h of size n filled with 0.0 now because resize() takes much more time
    } // constructor
};

int main() {
    vector<double> h(10, 0.0);  // what I would like to make happen inside of the struct
    Struct_w_Vector v(10);
    return 0;
}

是否可以将名为hdoublevector 的大小设置为n 在构造时填充全0(不使用调整大小)?

感谢您的宝贵时间。

【问题讨论】:

    标签: c++ object vector struct


    【解决方案1】:

    这将实现你所需要的:

    Struct_w_Vector(int n) : n(n), h(n) {}
    

    这很接近,但在标准 C++ 中不允许使用括号,此外,n 在此时未初始化:

    vector<double> h(n, 0.0);
    

    所以最好放下它。

    请注意,您可能不需要存储n,因为您始终可以使用h.size() 获取向量的大小。您也不需要声明析构函数。剩下的就是

    struct Struct_w_Vector {
        vector<double> h;
        Struct_w_Vector(int n) : h(n) {}
    };
    

    【讨论】:

      【解决方案2】:

      为什么不将“h”设为指针并在构造函数中使用新向量对其进行初始化?

      struct Struct_w_Vector {
          ~Struct_w_Vector() {
              delete h;
          } // destructor
      
          int n;
          vector<double> *h;
      
          Struct_w_Vector(int n) : n(n) {
              h = new vector<double>(n, 0.0);
          } // constructor
      };
      

      【讨论】:

      • Bjarne 说使用 new 通常不是一个好主意。 (我没有投反对票。)这是唯一的选择吗?
      • 1.在这种情况下不需要new,只需在结构构造函数的成员初始化列表中初始化h(参见juanchopanza's answer)。 2. 通过使用new,但省略了复制/移动构造函数和复制/移动赋值操作符来正确管理指针,这个结构违反了Rule of 3/5/0,它可以导致各种问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多