FR_MPI
FR_MPI

Reputation: 131

Compiler does not recognize member initializer for std::vector

I want to initialize a std::vector to have a specific length. in the .hpp file I use

#include <vector>

class foo
{
foo(){};
~foo(){};
std::vector<double> pressure (4,0); //vector 4 elements = 0

void readPressure()
{
    pressure.at(0) = 1;
    pressure.at(1) = 2;
    pressure.at(2) = 3;
    pressure.at(3) = 4;
}
...
};

But I get the error:

error: expected identifier before numeric constant
std::vector<double> pressure(4,0);
                             ^
error: expected ',' or '...' before numeric constant

I read that this might be due to not using C++11 but I specify in my makefile

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_FLAGS_RELEASE "-O3")

I am compiling on a raspberry 4, g++ version is 8.3

***edited the .hpp file

Upvotes: 2

Views: 163

Answers (1)

songyuanyao
songyuanyao

Reputation: 172934

Default member initializer (since C++11) only supports brace and equal-sign initializer. E.g.

class foo
{
    std::vector<double> pressure = std::vector<double>(4,0); //vector 4 elements = 0
    ...
};

BTW: We can't use braced-initializer as std::vector<double> pressure{4,0};, because it would initialize the vector containing 2 elements with value 4 and 0, which is not what you want.

Upvotes: 3

Related Questions