Hi, i have some code that compares a string like ten times and accordinly to that string a type is returned:
Code:
Server::MessageTypes Server::getMessageType(const char* message)
{
int index = strcspn(message, " ");
char* command = new char[index + 1];
strncpy(command, message, index);
command[index] = '\0';
if (strcmp(command, "AUTH") == 0)
{
delete [] command;
return AUTH;
}
else if (strcmp(command, "QUERY") == 0)
{
delete [] command;
return QUERY;
}
else
{
delete [] command;
return INVALID;
}
}
But i wanted to make this code more flexible by using C++ maps. For example: a person adds a key like: "APPVER" in the map and the value will be a int APPVER (defined in a enum). So i came up with the following code:
Code:
void Server::addCommand(const char* command, int id)
{
map[command] = id;
}
Server::MessageTypes Server::getMessageType(const char* message)
{
int index = strcspn(message, " ");
char* command = new char[index + 1];
strncpy(command, message, index);
command[index] = '\0';
int value = map[command];
delete [] command;
return value;
}
But i was a litlle afraid, since this function is called many times, of this map solution decreasing my performance. I wanted a suggestion...
Thank you.