Thursday, November 1, 2012

Minor Change – Vector vs. Map

One of the changes made to the test code was to put the names of each test mode into a QMap where the enumeration name for the test mode is associated with the name of the test mode (as a QString).  This was the original code (the array is then indexed by the enumeration value) and the names were declared separate so there could be referenced directly (though the name[] could have been used to get the names):
char parser_name[] = "parser";
char expression_name[] = "expression";
char translator_name[] = "translator";
char *name[] = {
    parser_name, expression_name, translator_name
};
The problem with this code is that the programmer must insure that the correct names are placed in the array in the correct order matching the enumeration values, otherwise the wrong name will be used.  This is also basically why the Code and TokenStatus enumerations are automatically generated - to eliminated possible coding errors.  Using QMap was a way to eliminate this possibility.  This was the resulting code (the map is still indexed by the enumeration value) and the name map was used to access the names:
QMap<testModeEnum, QString> name;
name[testParser] = "parser";
name[testExpression] = "expression";
name[testTranslator] = "translator";
However, the enumeration declaration had to moved outside the function or it would not compile (apparently, local enumerations can be used).  In later considering this code, a better method would be to use a pre-sized QVector since a QMap has more overhead that is really not needed here and the enumeration values are in order.  The code was changed to the nearly identical:
QVector<QString> name(sizeofTestMode);
name[testParser] = "parser";
name[testExpression] = "expression";
name[testTranslator] = "translator";
Where the sizeofTestMode value was added to the end of the enumeration (which was moved back into the function) so that the vector could be allocated ahead of time.  Using QMap would be needed if the indexes being associated were not in numerical order.

[commit  ad08201092]

No comments:

Post a Comment

All comments and feedback welcomed, whether positive or negative.
(Anonymous comments are allowed, but comments with URL links or unrelated comments will be removed.)