On Sun, 26 Aug 2007 11:03:36 +0000, Erik Wikstr??m wrote:
On 2007-08-26 11:20, Paul Brettschneider wrote:
Hello,
I have a global static array of structs and want to access a given
element using an identifier. I don't want to use the element subscript,
because it will change if I insert elements before the element I
want to access. In assembler I would simply add a label in front
of the element, but this doesn't work in C++.
[...]
Is there a way to do this in C++ (maybe some preprocessor tricks)?
There are probably some pre-processor trick you can use, but I suspect
that would be the wrong solution. Since you mentioned assembly I suspect
you have a background with that and might thus not be very familiar with
the C++ way of doing things. If you could explain a little bit about
what you are trying to solve I might be able to give you better advice.
I have, for example, a number of "Server-Objects" which are registered
when connecting to the server and can be used afterwards. When registering
or when generating statistics, it is convenient to loop over an array,
later I want to access them by name.
What I do right now is define global objects and then construct an array
of pointers:
static A element_a = { "a" };
static A element_b = { "b" };
static A element_c = { "c" };
static A *array[] = {
&element_a,
&element_b,
&element_c,
// ...
NULL // sentinel
};
You could use std::map<std::string, A> servers. Then you could access a
elements perhaps they should not be in an array.