如何从映射值初始化 Int,C++

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

我在 header 电子游戏中的武器名称和 ID 号中有一张大型全球地图。我正在尝试找到一种方法,让用户输入名称和 return 项目编号。为此,我创建了一个新的 int 并希望在搜索名称后使用地图值对其进行初始化。执行此操作的最佳方法是什么?

//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;

好吧,您的代码中似乎存在多种误解:

//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;
}

看到一个live demo


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

在这种情况下,您需要将初始化从全局上下文中移出:

int main() {
     std::string weaponType;

     std::cout "Input a weapon type: "
     std::cin >> weaponType;

     int swapWeapon = globalMap()[weaponType];
     std::cout << swapWeapon;
}

更多积分

  • 不要在头文件中使用 using namespace std;(参见 here 原因)
  • 一般来说,避免使用这样的扁平化 Singleton Patterns, rather use a Abstract Factory 以使您的代码在未来的维护中更加灵活。