简体   繁体   English

使用声明时的值初始化2D向量

[英]Initialising a 2D vector with values at declaration

I'm currently working on a program which randomly generates items (eg weapons, armour etc.) and I want to make global constant vectors which hold all the names that could be given to the items. 我目前正在开发一个程序,该程序随机生成物品(例如武器,装甲等),并且我想制作全局常数矢量,其中包含可以赋予物品的所有名称。 I want to have this 2D vector in a header file that's available to all my other classes (but not modifiable), so I need to initialise it at declaration. 我想在所有其他类都可以使用(但不可修改)的头文件中包含2D向量,因此我需要在声明时对其进行初始化。

I previously used the following: 我以前使用以下内容:

static const std::string v[] =
{
    "1.0", "1.1", "1.2", "null"
};
const std::vector<std::string> versions( v, v+sizeof( v)/sizeof( v[0]));

This worked for a 1D vector, however I want to use a 2D vector to store item names. 这适用于1D向量,但是我想使用2D向量存储项目名称。

I have tried using the following however it means I don't have the member functions (such as size()): 我尝试使用以下内容,但这意味着我没有成员函数(例如size()):

static const std::string g_wn_a[] = { "Spear", "Lance", "Jouster" };
static const std::string g_wn_b[] = { "Sword", "Broadsword", "Sabre", "Katana" };
const std::string* g_weapon_names[] = { g_wn_a, g_wn_b };

I also don't want to use a class to store all the names because I feel it would be inefficient to have variables created to store all the names everytime I wanted to use them. 我也不想使用一个类来存储所有名称,因为我觉得每次我想使用它们创建变量来存储所有名称的效率都不高。

Does anyone know how I can solve my problem? 有人知道我能解决我的问题吗?

You could use a class with const static members. 您可以使用具有const static成员的类。 This way, your class would just behave like a namespace and you wouldn't have to create an instance of the name-holding class to use the names. 这样,您的类就像一个名称空间一样工作,而不必创建名称持有类的实例来使用名称。

struct MyNames {
    // const static things
    const static string myweapon = "Katana"
};

string s = MyNames::myweapon; // s = "Katana"

This is C++, so the most common way to do this is to write a class that does this in its constructor, and then create a const object of that class. 这是C ++,因此最常用的方法是编写一个在其构造函数中执行此操作的类,然后创建该类的const对象。 Your class would then provide various member functions to query the various items it maintains. 然后,您的类将提供各种成员函数来查询其维护的各种项目。

As a bonus, this will make it easier for the rest of your code to use the various items. 另外,这将使其余代码更易于使用各种项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM