Initializing a vector class member in C++
Asked Answered
P

2

8

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?

Polychasium answered 10/11, 2016 at 23:39 Comment(1)
in C++11, you can have default member values, but not in C++98. The syntax is vector<double> vec_ = vector<double>(5, 0.0f);Riches
E
13

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.

Emmanuel answered 10/11, 2016 at 23:45 Comment(0)
C
8

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

Coleridge answered 16/2, 2020 at 3:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.