首页 > 解决方案 > 如何从映射值初始化 Int,C++

问题描述

我在视频游戏的武器名称和 ID 编号的标题中有一张大型全球地图。我正在尝试找到一种方法,可以让用户输入名称并返回项目编号。为此,我创建了一个新的 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;

标签: c++initializationunordered-map

解决方案


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

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

观看现场演示


为此,我创建了一个新的 int,并希望在搜索名称后使用映射值对其进行初始化。

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

int main() {
     std::string weaponType;

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

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

更多积分

  • 不要using namespace std;在头文件中使用(见这里为什么)
  • 通常避免使用这种扁平的Singleton Patterns,而是使用抽象工厂来使您的代码更加灵活以供将来维护。

推荐阅读