Autogenerating Inverse Maps

The map class in the C++ standard library works like an associative array, mapping from one type collection to another for example from color names (“Red”, “Green”, “Blue) to RGB values (0xFF0000, 0×00FF00, 0×0000FF).

Sometimes you require to map both ways and while it is simple to generate the inverse map, it can be tedious to do it for lots of maps.

Here is a simple function with example usage, which given a map (for any mapping types) will generate the inverse map for you.

#include <string>
#include <iostream>
#include <iomanip>
#include <map>

template <class K, class V> std::map<V, K> MapInvertor(std::map<K, V> &amp;forwardMap)
{
    std::map<V, K> inverseMap;

    for (std::map<int, char *>::iterator iter = forwardMap.begin(); iter != forwardMap.end(); iter++)
    {
        inverseMap[iter->second] = iter->first;
    }

    return inverseMap;
}

int main(int arc, char *argv[])
{
    std::map<int, char *> rgbToColorName;
    std::map<char *, int> colorNameToRgb;

    rgbToColorName[0×000000] = "black";
    rgbToColorName[0×0000FF] = "blue";
    rgbToColorName[0×00FF00] = "green";
    rgbToColorName[0×800080] = "purple";
    rgbToColorName[0xFF0000] = "red";
    rgbToColorName[0xC0C0C0] = "silver";
    rgbToColorName[0xFFFFFF] = "white";
    rgbToColorName[0xFFFF00] = "yellow";
    rgbToColorName[0xFFD700] = "gold";

    for (std::map<int, char *>::iterator iter = rgbToColorName.begin();
iter != rgbToColorName.end(); iter++)
    {
        printf("RGB 0x%06x is the colour %s\n", iter->first,iter->second);
    }

    printf("\n");

    colorNameToRgb = MapInvertor(rgbToColorName);

    for (std::map<char *, int>::iterator iter = colorNameToRgb.begin();
iter != colorNameToRgb.end(); iter++)
    {
        printf("Color %s has the RGB value 0x%06x\n", iter->first, iter->second);
    }

    return 0;
}

The output is

RGB 0×000000 is the colour black
RGB 0×0000ff is the colour blue
RGB 0×00ff00 is the colour green
RGB 0×800080 is the colour purple
RGB 0xc0c0c0 is the colour silver
RGB 0xff0000 is the colour red
RGB 0xffd700 is the colour gold
RGB 0xffff00 is the colour yellow
RGB 0xffffff is the colour white

Color black has the RGB value 0×000000
Color blue has the RGB value 0×0000ff
Color green has the RGB value 0×00ff00
Color purple has the RGB value 0×800080
Color red has the RGB value 0xff0000
Color silver has the RGB value 0xc0c0c0
Color white has the RGB value 0xffffff
Color yellow has the RGB value 0xffff00
Color gold has the RGB value 0xffd700