如何设置全局容器(C ++ 03)? [英] How to setup a global container (C++03)?

查看:674
本文介绍了如何设置全局容器(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 ++中的全局对象定义

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.

这篇关于如何设置全局容器(C ++ 03)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆