Search code examples
c++initializationunordered-map

How to initialize an Int from a map Value, C++


I have a large global map in a header of weapon names and ID numbers from a video game . I am trying to find a way that I can take user input for the name and return the item number. For this I created a new int and would like to initialize it with the map value after searching for the name. What is the best way to do this?

//header
#include <map>
#include <string>

using namespace std;
typedef std:: map <std :: string, int> weaponMap;

inline
weaponMap & globalMap() {
    static weaponMap theMap;
    static bool firstTime = true;
    if (firstTime) {
    firstTime = false;
      theMap["weaponOne"] = 854000;

    }
}


//Source.cpp

#includes "globalMap"

int swapWeapon = weaponMap::["weaponOne"];
    cout << swapWeapon;

Solution

  • Well, there are multiple misconceptions you seem to have in your code:

    //header
    #include <map>
    #include <string>
    
    using namespace std;
    typedef std:: map <std :: string, int> weaponMap;
    
    inline
    weaponMap & globalMap() {
        static weaponMap theMap;
        static bool firstTime = true;
        if (firstTime) {
        firstTime = false;
          theMap["weaponOne"] = 854000;
        }
        return theMap; // this is necessary if you specify a return type
    }
    

    //Source.cpp
    
    // #includes "globalMap" You have a typo here, that should be as follows
    #include "globalMap"
    
    // You cannot access the local static variable from the function in your code directly
    // int swapWeapon = weaponMap::["weaponOne"]; 
    
    int swapWeapon = globalMap()["weaponOne"]; // Note that this would initialize
                                               // swapWeapon with 0 if "weaponOne"
                                               // wasn't registered as a key
    
    // You cannot use these statements outside of a function scope
    //   cout << swapWeapon;
    
    int main() {
         cout << swapWeapon;
    }
    

    See a live demo.


    For this I created a new int and would like to initialize it with the map value after searching for the name.

    In that case you need to move the initialization out from the global context:

    int main() {
         std::string weaponType;
    
         std::cout "Input a weapon type: "
         std::cin >> weaponType;
    
         int swapWeapon = globalMap()[weaponType];
         std::cout << swapWeapon;
    }
    

    More points

    • Do not use using namespace std; in header files (see here why)
    • In general avoid to have such flat Singleton Patterns, rather use a Abstract Factory to make your code more flexible for future maintenance.