is std::map appropriate here?

Hi

I have a function where one of the arguments needs to be a series of associations between an enum and a double. Each enum will be unique but enums may have the same value for their double.

I think that std::map is appropriate here as this can contain unique enums mapped to the doubles. However, I am reluctant to use it as I've always had the idea that std::map is quite a 'big' class. I'm only using it to contain maybe 5 - 10 enums - do you think std::map is unnecessary? Should I use something else or just have a vector of pairs?

Any thoughts appreciated

Thanks
That depends. You may be able to do something as simple as this:

1
2
3
4
5
6
7
8
9
10
#include <iostream>

enum {ZERO, ONE, TWO, THREE};

int main()
{
    double value[] = {0.0, 1.1, 2,2, 3,3};
    
    std::cout << value[TWO] << '\n';
}

I've always had the idea that std::map is quite a 'big' class

You have an engineering decision to make. There is a right answer, and unless your "idea" is actually objective fact (e.g., instantiation Y greatly increases code size on implementation X), it should probably be set aside.

You need to consciously answer these questions, then decide:
- What does std::map offer your program?
- What does std::map cost your program?

The costs may be minor or even irrelevant. But this isn't necessarily true.
What about the benefits? Will it make your code more readable, or reduce the likelihood of an error?

The rule-of-thumb is "prefer solutions in the standard library".

There are parts of any given program that need to be designed with more care - interfaces, for example, deserve more care in their high-level design than the localized guts of one particular function. Implementations are easy to change, but interfaces are not. Is this decision worth the time you're taking on it?
Last edited on
I've always had the idea that std::map is quite a 'big' class

Few classes in the Standard Library are very big, by any definition.

mbozzi’s advice is absolutely correct, but I would clarify to specifically say use the map, unless you have a very obvious reason not to.
Sorry, when I said functions I really meant a public method of the object. So I think it is an interface and perhaps the client/user shouldn't be using a map?
If the map makes the user’s life harder, then don’t use it.

However, for any associate array, using a common type is preferable to rolling anything special. And, by using a common type, the user will likely be using it elsewhere, also reducing code bloat.

Use the map.
Topic archived. No new replies allowed.