I have small question about std::vector. In main.h i try to make fixed size int vector
std::vector<int> foo(7);
But g++ gived this error:
../test/main.h:21:26: error: expected identifier before numeric constant
std::vector<int> foo(7);
../main/main.h:21:26: error: expected ',' or '...' before numeric constant
How can i create private vector variable of fixed size length? Or should i simply make in constructor
for(int i=0; i<7;i++){
foo.push_back(0);
}
Assuming
foo
is a data member, your syntax is invalid. In general, you can initialize a data member of type T like this:or this
However,
std::vector<int>
has a constructor that takes anstd::initializer_list<int>
, which means that the first form would yield a size-1 vector with a single element of value 7. So you are stuck with the second form:If you are stuck with a pre-C++11 compiler, you would need to use a constructor:
and take care to initialize the vector in all constructors (if applicable.)
The most efficient way to initialize a class member (other than built-in type), is to use the initialisation list.
So the best solution here, is to construct your vector of length 7 in the initilization list of your class constructor:
(I also recommend you to use a define for your fixed value 7. If you change it to 8 in the futur your will not have to change the value 7 on all your code)
file.h:
file.cpp :