I am attempting to reserve memory for a med_array vector as seen below
vector <int> med_array = {};
med_array.reserve(50000);
MedianFinder();
void addNum(int num);
double findMedian();
vector<int> get_array();
void print_array();
However, I get an error stating:
medianfinderheader.h:10:4: error: 'med_array' does not name a type
10 | med_array.reserve(50000);
I have no idea why this is happening.
CodePudding user response:
I figured it out .reserve needs to be run inside a function I can't define in the class header like I was trying to do.
CodePudding user response:
Taking into account the error message, these lines:
vector <int> med_array = {};
med_array.reserve(50000);
are in a (global) namespace where you may place only declarations. But this line:
med_array.reserve(50000);
is not a declaration. So the compiler issues the error. That is, the compiler tries to interpret the line as a declaration, but the name med_array
is not a type specifier.
From the C 20 Standard (9.8 Namespaces)
1 A namespace is an optionally-named declarative region. The name of a namespace can be used to access entities declared in that namespace; that is, the members of the namespace. Unlike other declarative regions, the definition of a namespace can be split over several parts of one or more translation units.
Pay attention to that this declaration:
vector <int> med_array = {};
can be written simpler, like:
vector <int> med_array;
Or, you could initially declare the vector with 50000 elements, like:
vector <int> med_array( 50'000 );