Bas Nedermeijer <ba*@tdlnx.student.utwente.nlwrote:
what is a efficient solution to compare a string against a lot of
possiblities?
Currently i am having a lot of
if (strcmp(checkme, "option1", strlen(checkme))) {
value = OPTION1;
}
is there an other option? Or can i (ab)use a map or something for this?
Only then i would have the problem of filling the map first on every
call (or use a global).
I am using the current setup to gather input from keyboard / remote and
network. So i can handle the commands on a central place.
Suggestions welcome
Time to have FUN WITH FUNCTORS that fabulous game show in which you can
amaze your programmer friends with your esoteric knowledge. :-)
const char* opt[] = { "opt1", "opt2", "opt3" }; // continue as needed
enum options { opt1, opt2, opt3, numOpts };
// ignore what's behind the curtain, just enjoy how easy
// this is to use in the "find_option_for" function
struct c_str_equal_to :
unary_negate<binder1st<pointer_to_binary_function< const char*,
const char*, int >
{
c_str_equal_to( const char* value ) :
unary_negate<binder1st<pointer_to_binary_function< const char*,
const char*, int >( bind1st( ptr_fun( &strcmp ), value ) )
{ }
};
// in debug, we first make sure there are no programming mistakes
// returns the correct option for the string passed in
options find_option_for( const char* value ) {
assert( find_if( opt, opt + numOpts, c_str_equal_to( value ) ) !=
opt + numOpts );
return (options)distance( opt, find_if( opt, opt + numOpts,
c_str_equal_to( value ) ) );
}
int main() {
options value = find_option_for( "opt3" );
assert( value == opt3 );
char checkme [4];
strcpy( checkme, "opt2" );
value = find_option_for( checkme );
assert( value == opt2 );
}
Seriously though, maybe you should just put the "checkme" value into a
std::string and use it directly instead of converting it to an enum (or
whatever type 'value' is.)
--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.