declaring a vector

Write your question here.
I'm using code::blocks
and i am getting this error :
||=== Build: Debug in newbase (compiler: GNU GCC Compiler) ===|
C:\mc\le_c\newbase\adefs.hpp|37|error: expected identifier before numeric constant|
1
2
3
  Put the code you need help with here.
std::vector<int> pcmap;     /* gets compiled */
std::vector<int> pcmap(10); /* gives me the above error */ 
You cannot initialize member variables with parentheses directly in the class definition.

You need to use =
1
2
3
4
struct A
{
	std::vector<int> pcmap = std::vector<int>(10); 
};

or {}
1
2
3
4
struct B
{
	std::vector<int> pcmap {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 	
};


But if you put the initialization in the member initializer list of the constructor you can use parentheses.
1
2
3
4
5
struct C
{
	C() : pcmap(10) {}
	std::vector<int> pcmap; 
};
Last edited on
Thanks for the very topical and speedy answer.

First and second examples compile nicely while with the next code example, I'm not sure about creating a variable like C mystuff();

Dabbling in C++03 native arrays will do that to you.
How did we get from int pcmap[ 10 ] to the above not cool stuff.

Michel Chassey
In C++03 it wasn't possible to initialize member variables directly (except for static const ones). You had to do it in the constructor. C++11 added default member initializers which allows you to initialize members directly when defining them, using {} or =. Unfortunately it is not possible to use parentheses, probably because it would break old code due to the most vexing parse (https://en.wikipedia.org/wiki/Most_vexing_parse) perhaps because it would look too much like a member function declaration. For most situations this is not a problem because you can often just replace the parentheses with {} and it will work fine. One exception is containers which uses {} to initialize the container with a list of values.

If pcmap will always have exactly 10 elements it's probably better to simply use an array (a raw array or std::array).
1
2
3
4
5
6
#include <array>

struct D
{
	std::array<int, 10> pcmap {};
};
Last edited on
Thanks for further clarifying, and your patience.
I have pretty printed your posts and inserted the printout in my "good" book.
This is where I got the idea for the broken code. ( " list<float> lf( 5 ); " ).
Topic archived. No new replies allowed.