Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing a vector class member in C++

I'm trying to set length and initialize a vector member of a class, but it seems it's only possible if initializing line is out of class.

//a vector, out of class set size to 5. initialized each value to Zero
vector<double> vec(5,0.0f);//its ok

class Bird{

public:
    int id;
    //attempt to init is not possible if a vector a class of member
    vector<double> vec_(5, 0.0f);//error: expected a type specifier
}

How can I do this inside the class?

like image 316
Zen Of Kursat Avatar asked Nov 10 '16 23:11

Zen Of Kursat


2 Answers

Use the Member Initializer List

class Bird{

public:
    int id;
    vector<double> vec_;

    Bird(int pId):id(pId), vec_(5, 0.0f)
    {
    }
}

This is also useful for initializing base classes that lack a default constructor and anything else you'd rather have constructed before the body of the constructor executes.

like image 141
user4581301 Avatar answered Oct 10 '22 21:10

user4581301


As Franck mentioned, the modern c++ way of initializing class member vector is

vector<double> vec_ = vector<double>(5, 0.0f);//vector of size 5, each with value 0.0

Note that for vectors of int, float, double etc (AKA in built types) we do not need to zero initialize. So better way to do this is

vector<double> vec_ = vector<double>(5);//vector of size 5, each with value 0.0

like image 21
Gaurav Avatar answered Oct 10 '22 21:10

Gaurav