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:Output
The only real problem, if you can call it that, is the extra global variable.