vte*_*al3 2 c++ hash hashmap hash-of-hashes
有没有一种方法可以在C ++中创建哈希哈希?
实际上,我正在尝试做您可以在Perl中完成的工作,但仅限于C ++。这是我想在C ++中发生的Perl代码示例
%hash = (
gameobject1 => {
position => {
x_loc => 43,
y_loc => 59,
}
rect_size => {
width => 5,
height => 3,
}
collidable => 1,
sounds => {
attack => "player_attack.ogg",
jump => "player_jump1.ogg",
jump_random => [qw/player_jump1.ogg player_jump2.ogg player_jump3.ogg/]
}
},
gameobject2 => {
position => {
x_loc => 24,
y_loc => 72,
}
rect_size => {
width => 2,
height => 4,
}
sounds => {
attack => "goblin_attack.ogg",
}
items => [qw/sword helmet boots/]
},
);
Run Code Online (Sandbox Code Playgroud)
要注意的是,游戏对象中的哈希值可以存在或不存在……即位置可能存在于gameobject1中,但可能不存在于gameobject35中。
有任何想法吗?
Perl散列使您可以使用任何值。C ++是一种静态类型的语言,它不会让您这样做:您必须确切指定希望散列中的值(在C ++术语中,映射)具有的类型。
这是C ++ 11和boost的可能解决方案,其中包含一些强类型:)
#include <map>
#include <vector>
#include <string>
#include <boost/optional.hpp>
// Coordinates are always like this, aren't they?
struct coords {
int x_loc;
int y_loc;
};
// Dimensions are always like this, aren't they?
struct dims {
int width;
int height;
};
// Sound maps: each string key maps to a vector of filenames
typedef std::map<std::string, std::vector<std::string>> sound_map;
// Item lists: looks like it's just a collection of strings
typedef std::vector<std::string> item_list;
// Fancy names to improve readability
enum collidability : bool {
collidable = true,
not_collidable = false
};
// A structure to describe a game object
struct game_object {
// An optional position
boost::optional<coords> position;
// An optional rectangle size
boost::optional<dims> rect_size;
// Assuming "false" can mean the same as "no collidable key"
bool collidable;
// Assuming an "empty map" can mean the same as "no map"
sound_map sounds;
// Assuming an "empty vector" can mean the same as "no vector"
item_list items;
// If any of the above assumptions is wrong,
// sprinkle boost::optional liberally :)
};
// Finally, values for our "hash"
std::map<std::string, game_object> hash {
{ "game_object1",
{
coords { 43, 59 },
dims { 5, 3 },
collidable, // remember those fancy names?
sound_map {
{ "attack", { "player_attack.ogg" } },
{ "jump", { "player_attack.ogg" } },
{ "jump_random", { "player_jump1.ogg", "player_jump2.ogg", "player_jump3.ogg" } }
},
item_list {}
} },
{ "game_object2",
{
coords { 24, 72 },
dims { 2, 4 },
not_collidable,
sound_map {
{ "attack", { "goblin_attack.ogg" } }
},
item_list { "sword", "helmet", "boots" }
} },
{ "game_object25",
{
boost::none, // no position
dims { 2, 4 },
not_collidable,
sound_map {
{ "attack", { "goblin_attack.ogg" } }
},
item_list { "sword", "helmet", "boots" }
} }
};
Run Code Online (Sandbox Code Playgroud)
如果您确实想要类似Perl散列的Perl散列之类的东西,则可以使用std::map<std::string, boost::any>来在地图中存储任何内容。但是,这要求您先测试每个值的类型,然后再从地图中获取它。如果只能使用某些类型的集合,则可以使用比更为强类型的东西boost::any,例如boost::variant。