Tom Lilletveit
Tom Lilletveit

Reputation: 2002

C++: Design: should I use enum here?

What is the preferred and best way in C++ to do this: Split the letters of the alphabeth into 7 groups so I can later ask if a char is in group 1, 3 or 4 etc... ? I can of course think of several ways of doing this myself but I want to know the standard and stick with it when doing this kinda stuff.

0
AEIOUHWY
1
BFPV
2
CGJKQSXZ
3
DT
4
MN
5
L

6
R

Upvotes: 0

Views: 117

Answers (3)

user93353
user93353

Reputation: 14049

Create a lookup table.

int lookup[26] = { 0, 1, 2, 3, 0, 1, 2, 0 .... whatever };

inline int getgroup(char c)
{
    return lookup[tolower(c) - 'a'];
}

call it this way

char myc = 'M';
int grp = lookup(myc);

Error checks omitted for brevity.

Of course, depending on what the 7 groups represent , you can make enums instead of using 0, 1, 2 etc.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490663

Given the small amount of data involved, I'd probably do it as a bit-wise lookup -- i.e., set up values:

cat1 = 1;
cat2 = 2;
cat3 = 4;
cat4 = 8;
cat5 = 16;
cat6 = 32;
cat7 = 64;

Then just create an array of 26 values, one for each letter in the alphabet, with each containing the value of the category for that letter. When you want to classify a letter, you just categories[ch-'A'] to find it.

Upvotes: 1

Tony Delroy
Tony Delroy

Reputation: 106246

best way in C++ to do this: Split the letters of the alphabeth into 7 groups so I can later ask if a char is in group 1, 3 or 4 etc... ?

The most efficient way to do the "split" itself is to have an array from letter/char to number.

//                      A  B  C  D  E  F  G  H...
const char lookup[] = { 0, 1, 2, 3, 0, 1, 2, 0...

A switch/case statement's another reasonable choice - the compiler can decide itself whether to create an array implementation or some other approach.

It's unclear what use of those 1-6 values you plan to make, but an enum appears a reasonable encoding choice. That has the advantage of still supporting any use you might have for those specific numeric values (e.g. in < comparisons, streaming...) while being more human-readable and compiler-checked than "magic" numeric constants scattered throughout the code. constant ints of any width are also likely to work fine, but won't have a unifying type.

Upvotes: 2

Related Questions