Perl的哈希,讓你使用任何值。 C++是一種靜態類型語言,它不會讓你這麼做:你必須明確指定你希望哈希中的值(用C++語言,地圖)的類型。
下面是用C++ 11和升壓可能的解決方案,與一些有實力的打字:)
#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" }
} }
};
拋出如果你真的想要的東西如Perl的一個Perl哈希散列,你可以使用std::map<std::string, boost::any>
得到在地圖上存儲任何東西的能力。但是,這需要您在從地圖獲取每個值之前測試每個值的類型。如果只有一組類型是可能的,則可以使用比boost::any
更強的類型,如boost::variant
。
因爲C和C++是不同的語言,所以我在你的問題中用「C++」替換了「c/C++」。如果我的假設錯了,請糾正我,而您實際上對C解決方案感興趣。 – 2012-01-10 05:55:12
我很喜歡任何一種,或者哪種有意義的東西:) C++作品 – vternal3 2012-01-10 05:56:37