I need to compare one string to nearly 60 other strings in real-time. Right now I'm doing this:
1 2 3 4 5 6 7
if (str.compare("somestring") == 0)
DoSomething();
elseif (str.compare("anotherstring") == 0)
DoSomethingElse();
// 60 or so else..ifs later
else
DoSomeOtherThing();
It works, but you can sort of notice the lag. Is there any fast method to compare a string to many other strings?
In any case as I have understood you must compare str with each string literal until you find the exact match. Only I would use == operator instead of the member function compare.
If you could have all string literals in a sorted array then you could use the binary search and switch statement for the index of the array.
@ne555: The strings are being compared in the graphics thread in a game. Unfortunately, this part of the code could not be put on a separate thread because the subsequent action taken by the graphics engine relies on the input provided here.
The strings are being compared in the graphics thread in a game.
In that case, rather than comparing strings you should probably keep a symbol table (a mapping from strings to numbers) around. String comparisons can be rather costy, number comparisons not so much. While doing a few thousand string comparisons per second still isn't likely to be a bottleneck, you could definitely save some cycles there if you really have to.