Defining maps in another file?

For example: I’m trying to make a map object that relates pitch names (“C#”, “Gb”, “E”, etc.) to their midi equivalents (25, 30, 28, etc.). I’ve accomplished this successfully with:


map<string, int> midiTable;


midiTable["C"]  = 24;
midiTable["C#"] = 25;
midiTable["Db"] = 25;
midiTable["D"]  = 26;
midiTable["D#"] = 27;
midiTable["Eb"] = 27;
midiTable["E"]  = 28;
midiTable["F"]  = 29;
midiTable["F#"] = 30;
midiTable["Gb"] = 30;
midiTable["G"]  = 31;
midiTable["G#"] = 32;
midiTable["Ab"] = 32;
midiTable["A"]  = 33;
midiTable["A#"] = 34;
midiTable["Bb"] = 34;
midiTable["B"]  = 35;

With Python, I’d put that in another file and import it as a module. How would I go about doing something similar in C++, and should I?

Another implementation would be for named colors.

Why do you want the map defined in a different file? The best solution I can think of is creating a MidiMap class and parsing a file that has pairs, like:

C 24
C# 25

And then initializes the map.

…I got curious about this and came up with the following header file:

class midiTable
	static int getMidi(string name)
		static midiTable instance;
		return instance.midimap[name];
	map<string, int> midimap;
		midimap.insert(std::pair<string,int>("a", 1));
		midimap.insert(std::pair<string,int>("b", 2));
		midimap.insert(std::pair<string,int>("c", 3));
		midimap.insert(std::pair<string,int>("d", 4));
		midimap.insert(std::pair<string,int>("e", 5));
	midiTable(midiTable const &);
	void operator=(midiTable const&);

There you can add definitions on the constructor as map insertions.

Note that I think this is overkill and it uses a singleton which might cause threading issues.

However it gives a comfy call:

int midi = midiTable::getMidi("C#");

That can be used from anywhere provided that you included the header.