I want to define a global container (C++03), and here's an example code I tried, which does not work.
#include <vector>
#include <string>
using namespace std;
vector<string> Aries;
Aries.push_back("Taurus"); // line 6
int main() {}
Compile error:
prog.cpp:6:1: error: 'Aries' does not name a type
It seems I can define an empty global vector, but cannot fill it up. Looks like in C++03, I cannot specify an initializer either, such as:
vector<string> Aries = { "Taurus" };
Have I made a mistake here, or how do I get around this problem?
I tried searching on StackOverflow to see if this has been answered before, but only came across these posts: global objects in C++, Defining global constant in C++, which did not help answer this.
I found a neat workaround to "initialize" C++03 global STL containers (and indeed to execute code "globally" before main()
). This uses the comma operator. See example:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
vector<string> Aries;
// dummy variable initialization to setup the vector.
// using comma operator here to cause code execution in global scope.
int dummy = (Aries.push_back("Taurus"), Aries.push_back("Leo"), 0);
int main() {
cout << Aries.at(0) << endl;
cout << Aries.at(1) << endl;
}
Output
Taurus
Leo
The only real problem, if you can call it that, is the extra global variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With