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

How to setup a global container (C++03)?(如何设置全局容器(C++03)?)
本文介绍了如何设置全局容器(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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

What is the proper function for comparing two C-style strings?(比较两个 C 风格字符串的正确函数是什么?)
Image Capture with OpenCV - Select Timeout Error(使用 OpenCV 捕获图像 - 选择超时错误)
SHA256 HMAC using OpenSSL 1.1 not compiling(使用 OpenSSL 1.1 的 SHA256 HMAC 未编译)
How to make a Debian package depend on multiple versions of libboost(如何制作一个Debian包依赖于多个版本的libboost)
Why does strcpy_s not exist anywhere on my system?(为什么我系统上的任何地方都不存在 strcpy_s?)
Simplest way to get current time in current timezone using boost::date_time?(使用 boost::date_time 在当前时区获取当前时间的最简单方法?)