Edward
Edward

Reputation: 235

Initialising a 2D vector with values at declaration

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?

Upvotes: 2

Views: 1309

Answers (2)

Nikos C.
Nikos C.

Reputation: 51832

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.

Upvotes: 0

alestanis
alestanis

Reputation: 21863

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"

Upvotes: 1

Related Questions