如何设置全局容器(C++03)?

2022-01-24 00:00:00 containers global-variables c++ c++03

我想定义一个全局容器(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() {}

编译错误:

prog.cpp:6:1: error: 'Aries' does not name a type

看来我可以定义一个空的全局向量,但无法填充它.看起来在 C++03 中,我也不能指定初始化器,例如:

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?

我尝试在 StackOverflow 上搜索以查看之前是否已回答过此问题,但只看到以下帖子:C++ 中的全局对象,在C++中定义全局常量,没有帮忙回答一下.

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.

推荐答案

我找到了一个巧妙的解决方法来初始化"C++03 全局 STL 容器(并且确实在 main()).这使用逗号运算符.见例子:

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;
}

输出

Taurus
Leo

唯一真正的问题是额外的全局变量.

The only real problem, if you can call it that, is the extra global variable.

相关文章