Perlのハッシュを使用すると、値のために何を使用してみましょう。 C++は静的に型指定された言語であるため、それを行うことはできません。ハッシュの値(C++のlingoではマップ)にどの型を指定するかを正確に指定する必要があります。あなたは本当にあなたが得るためにstd::map<std::string, boost::any>
を使用することができ、PerlはPerlのハッシュのようなものがハッシュたい場合は、いくつかの強い型付けがで:)
#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" }
} }
};
投げでここ
は、C++ 11とブーストで可能なソリューションですマップに何かを格納する能力。ただし、マップから取得する前に、すべての値の型をテストする必要があります。特定の種類のセットのみが可能な場合は、boost::any
より厳密に型指定されたもの、たとえばboost::variant
を使用できます。
私はあなたの質問の "c/C++"を "C++"に置き換えました。なぜならCとC++は異なる言語であるからです。私の前提が間違っていて実際にはCのソリューションに興味があるのなら、私を修正してください。 –
私はどちらかに行き着くか、それともこれまでに感銘を受けました:) C++の作品 – vternal3