C++ Allocate Vector Size in class variable without default initialization

后端 未结 2 1765
花落未央
花落未央 2021-01-21 07:00

So I have a class (HostObject) that has a vector of complex classes (object1) inside it. Such as the pseudocode depicted below

#DEFINE ARRAY_SIZE 10
class HostOb         


        
2条回答
  •  粉色の甜心
    2021-01-21 07:31

    You could do this by calling reserve() in default constructor.

    #DEFINE ARRAY_SIZE 10
    class HostObject {
      //other member variables
      vector vec; //vec(ARRAY_SIZE);  // not here
    
      //default constructor
      HostObject() {
        //leave vector default constructed
        vec.reserve(ARRAY_SIZE);               // but here
      }
    
      //my custom constructor                  // no need to change, since push_back will increase size automatically
      HostObject(double parmeter1, double parameter2, doubleparameter3) {
    
        //some code doing some calculations 
    
        for (int i = 0; i 

    Also consider using static unsigned array_size = 10; as a member of class HostObject, so that you can change the size dynamically every time creating an object of HostObject.

    HostObject ho1;  // array size is 10
    HostObject::array_size = 20;
    HostObject ho2;  // array size is 20
    

提交回复
热议问题