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

后端 未结 2 1769
花落未央
花落未央 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:36

    There is no constructor for std::vector for for reserving capacity. The only way you can reserve capacity is to use reserve member function.

    #DEFINE ARRAY_SIZE 10
    class HostObject {
        //other member variables
        vector vec;
    
        //default constructor
        HostObject(){
            vec.reserve(ARRAY_SIZE);
        }
    
        //my custom constructor
        HostObject(double parmeter1, double parameter2, doubleparameter3) {
            vec.reserve(ARRAY_SIZE);
            //some code doing some calculations 
    
            for (int i = 0; i 

    Read more about std::vector

提交回复
热议问题