Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a global container (C++03)?

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.

like image 743
Masked Man Avatar asked Nov 28 '22 21:11

Masked Man


1 Answers

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.

like image 171
Masked Man Avatar answered Dec 05 '22 17:12

Masked Man