1

我定义了两个structs

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. 我怎样才能做到这一点?

4

3 回答 3

2

只需为包含该成员的类定义一个构造函数,然后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

于 2012-12-20T19:23:21.563 回答
1

accumulationEntry只是一种类型。您还没有该类型的对象,因此无需std::vector<spatialEntry>调整大小。大概你会在accumulationEntry你的accumulationTable. 你可以这样做:

accumulationTable.push_back(accumulationEntry());

完成此操作后,您可以调整vector包含在例如第 0 个元素中的大小,如下所示:

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

或者,您可以提供一个构造函数来accumulationEntry调整其pattern成员的大小:

struct accumulationEntry {
  // ...
  accumulationEntry()
  {
    pattern.resize(16);
  }
};
于 2012-12-20T19:21:46.200 回答
1
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);
 }
};
于 2012-12-20T19:26:38.387 回答