c++ - 如何从映射值初始化 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;
解决方案
好吧,您的代码中似乎存在多种误解:
//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,而是使用抽象工厂来使您的代码更加灵活以供将来维护。
推荐阅读
- javascript - 点数被错误计算
- javascript - 提交表单并使用 target='_top' 留在同一页面上
- c# - c# - 查找没有根元素的节点值
- html - 尝试使用 AngularJS 将编辑后的图像保存到我的本地计算机
- angular - Angular 2+ 条件通配符重定向
- mysql - MySQL:如何使用 ONLY COUNT() 和不使用 WHERE 子句获取 24 小时内发生的事件计数
- sqlcmd - 如何从 sql server pdw 中的 bat 文件中获取用户输入?
- python - 谁能举一个小例子来解释 tf.random.categorical 的参数?
- c# - 使用 c# 控制台实现数组的链表
- javascript - 获取随机不重复的颜色