How to setup a global container (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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何设置全局容器(C++03)?
基础教程推荐
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01