I am trying to define a nested map variable in a header file to use for key value lookup (or key, key value lookup since it is nested).
Apologies for being very new to C++ in general, let alone C++98. I have intermediate JavaScript experience, which might explain difficulties/habits.
I'm trying to insert spoken language translations into a UI using a nested map, something with a structure similar to this:
phrases["english"]["hello"] = "hi";
phrases["spanish"]["hello"] = "hola";
which will allow me to use phrases[selectedLanguage]["hello"] which will return(?) "hi" or "hola" depending on what selectedLanguage is set to.
This is so that a user can switch between languages while also allowing me to just change one translations.h file if/when needed.
I have a working version of the code which puts the map definitions within the .cpp code but I'd like to create something like a header file which defines my 'phrases' map variable so that I can separate language translations from the rest of the .cpp code.
My current working code looks like this:
UI.cpp:
void CScnMgr::InitScreens(){
// selectedLanguage is defined
string selectedLanguage = "spanish";
//phrases map is defined
map <string, map <string, string> > phrases;
phrases["english"]["hello"] = "hi";
phrases["spanish"]["hello"] = "hola";
// then later when i need to use either translation...
phrases[selectedLanguage]["hello"];
}
This works, but I assume this is bad practice because it is creating this object every time the screens are initialized and for reasons I'm unfamiliar with. But I want to put my phrases map into a header file.
This is giving me errors:
translations.h:
#include <string>
#include <map>
int main(){
map <string, map <string, string> > newPhrases;
map <string, string> spanish;
map <string, string> english;
spanish["hello"] = "hola";
english["hello"] = "hi";
newPhrases["spanish"] = spanish;
newPhrases["english"] = english;
return 0;
}
UI.cpp:
#include "translations.h"
void CScnMgr::InitScreens(){
int extern newPhrases;
// further down where I need to display to the UI...
newPhrases[selectedLanguage]["hi"]
}
Errors:
UI.cpp: error: no match for 'operator[]' in 'newPhrases[selectedLanguage]'
I certainly don't understand why putting "int" in 'int extern newPhrases' passes compiling, but that's why it is there, I gave it the type of the main() return. I don't feel very comfortable doing that.
So I've defined selectedLanguage as "english" so I would expect C++ to handle that as newPhrases["english"], but it seems like newPhrases isn't defined as I expect it to be after importing it from translations.h
I'd appreciate a way to make this code work but I'd also appreciate reasons why this is the wrong way to go about this. Thanks in advance!