2

I'm currently working on a program which randomly generates items (e.g. 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.

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.

I have tried using the following however it means I don't have the member functions (such as 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?

2 Answers 2

1

You could use a class with const static members. 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" 
Sign up to request clarification or add additional context in comments.

Comments

0

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. 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.