Use enumeration for index

Is it legal to use an enumeration as index for eg a vector? You're using the integer value of the enum, I've read to avoid that. But it's a lot easier then defining every single number.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>

using namespace std;

//the enumeration
enum INDEX { LEFT, RIGHT, UP, DOWN};

int main()
{
    //the vector
    vector<int> a;
    
    //reserve memory
    a.assign(4,0);
    
    //assign values
    a[LEFT]  = 0;
    a[RIGHT] = 5;
    a[UP]    = 10;
    a[DOWN]  = 15;
    
    //access values
    cout<<a[LEFT]<<endl
        <<a[RIGHT]<<endl
        <<a[UP]<<endl
        <<a[DOWN]<<endl;
    
    //pause before exit
    cin.ignore();
    
    return 0;
}
It is legal as enums are integral types and the indices should be of an integral type
I don't know whether it is 'legal' but on my Linux system it compiles and runs.
Thanks for the replies.

It is legal as enums are integral types


What do you mean by integral types? Enums are always integral, right?

and the indices should be of an integral type


Aren't indices always integer?

What do you mean by integral types?
A numerical type which isn't floating point
Enums are always integral, right?
Yes
Aren't indices always integer?
For arrays, indices can be of any integral type, for containers they can be any type which can be implicitly casted to container::size_type (which is an unsigned integral type)
Oke, thanks.
Last edited on
Topic archived. No new replies allowed.