c++ - 调整结构中的 vector 的大小

标签 c++ vector

我定义了两个struct

class foo() {
public:
    struct spatialEntry {
        bool block;
        CoherenceState_t state;
    };

    struct accumulationEntry {
        uint64_t offset;
        std::vector<spatialEntry> pattern;
    };

    std::vector<int> v;
    std::list<accumulationEntry> accumulationTable;

    foo() {
        v.resize(16);
    }
};

现在我想初始化 std::vector<spatialEntry> 的大小到 16 喜欢 v .我该怎么做?

最佳答案

只需为包含该成员的类定义一个构造函数,然后将 resize() 定义为:

class foo() {
public:
   //...
   struct accumulationEntry 
   {
       uint64_t offset;
       std::vector<spatialEntry> pattern;
       accumulationEntry()
       {
            pattern.resize(16);  //<--------- this is what you want?
       }
    };
    std::vector<int> v;
    std::list< accumulationEntry > accumulationTable;
    foo()
    {
       v.resize(16);
    }
};

但是如果你使用 resize,那么最好这样做:

       accumulationEntry() : pattern(16)  //<--- note this
       {
            //pattern.resize(16);
       }

即,使用成员初始化列表。对 foo 也做同样的事情。

关于c++ - 调整结构中的 vector 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13978990/

相关文章:

c# - 关闭来自不同进程的套接字/端口连接

c++ - 如何在不暂停循环的情况下使用字符输入停止循环

c++ - C++中的POSIX线程编程

algorithm - Modelica:将数组返回值分配给标量

c++ - 6x6 数独游戏,找出你所在的部门

c++ - 指向抽象类的指针

c++ - 创建 vector 时的默认值,C++

c++ - 如何从文件中生成 "2 dimentional vector"行 X 字?

c++ - 在C++中,如何正确获取指向 vector 的共享指针,最大限度地减少复制构造函数的调用次数?

c++ - 将关键点转换为 mat 或将它们保存到文本文件 opencv