简体   繁体   English

调整结构中的向量的大小

[英]resizing a vector which is in a struct

I have defined two struct s 我已经定义了两个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);
    }
};

Now I want to initialize the size of std::vector<spatialEntry> to 16 like v . 现在我想将std::vector<spatialEntry>的大小初始化为16,如v How can I do that? 我怎样才能做到这一点?

Just define a constructor for the class which contains that member and then resize() as: 只需为包含该成员的类定义构造函数,然后将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);
    }
};

But then if you use resize , then it is better to do that as : 但是如果你使用resize ,那么最好这样做:

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

That is, use member-initialization list. 也就是说,使用成员初始化列表。 Do the same for foo also. 也为foo同样的事。

accumulationEntry is just a type. accumulationEntry只是一种类型。 You don't yet have an object of that type, so there is no std::vector<spatialEntry> to resize. 您还没有该类型的对象,因此没有std::vector<spatialEntry>来调整大小。 Presumably you will be adding accumulationEntry s to your accumulationTable . 大概你会加入accumulationEntry s到您的accumulationTable You might do that like this: 你可以这样做:

accumulationTable.push_back(accumulationEntry());

Once you have done that, you can resize the vector contained in, for example, the 0th element like so: 完成后,您可以调整包含在第0个元素中的vector ,如下所示:

accumulationTable[0].pattern.resize(16);

Alternatively, you could provide a constructor for accumulationEntry that resizes its pattern member: 或者,你可以提供一个构造函数accumulationEntry是重新调整其pattern成员:

struct accumulationEntry {
  // ...
  accumulationEntry()
  {
    pattern.resize(16);
  }
};
class foo() {
public:
 struct spatialEntry {
   bool block;
   CoherenceState_t state;
 };
 struct accumulationEntry {
 accumulationEntry()
     : pattern(16)  //  Calling pattern's c'tor
 {
 }
   uint64_t offset;
   std::vector<spatialEntry> pattern;
 };
 std::vector<int> v;
 std::list< accumulationEntry > accumulationTable;
 foo()
 {
    v.resize(16);
 }
};

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

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