Neonpeanut Neonpeanut - 4 months ago 10
C++ Question

Checking if a value is part of an existing set of values

I'm currently learning to code in C++, and I'm trying to find the best way to check if a given value is represented in a predefined set without having to iterate through the set.

For example, if I'm given a char, how can I check if it's a vowel or not without, say, iterating through an array containing the vowels? Would an enum work, or is there something else that is more efficient?

I know this is probably confusing, so if you need more details I can try to write some pseudo-code.


Well, your question is a bit vague but I will attempt to answer it. If the predefined set is a range or is otherwise defined by a neat formula, you obviously don't need iterating. In case of characters, for example, you can check if a given character is a lowercase Latin letter by :

if('a' <= myChar && myChar <= 'z')

But checking for a vowel will require iterating. But there are only 5 or six vowels, so why would you want to avoid iterating over them?

Also, if the predefined set is sorted, you don't need linear iteration. You can get away with a binary search, which will allow to determine if a value is among a set of 1000000 values by doing no more than 20 comparisons.