펄 해시는 값 아무것도 사용할 수 있습니다. C++은 정적으로 타입 된 언어이므로, 그렇게하지 못하게 될 것입니다 : 여러분은 해시 (C++ 용어, 맵에서)에 가질 값의 타입을 정확하게 지정해야합니다. 당신이 정말로, 당신이 얻을 std::map<std::string, boost::any>
를 사용하여 해쉬가 펄의 펄 해시 같은 것을 원하는 경우
여기에 :)
#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::variant
과 같이 boost::any
보다 강력한 형식의 것을 사용할 수 있습니다.
C 및 C++이 다른 언어이기 때문에 질문에서 "c/C++"를 "C++"로 바꿨습니다. 제 가정이 잘못되어 실제로 C 솔루션에 관심이 있다면 저를 고치십시오. –
나는 어느 쪽이든 또는 어떤 감각을 가지고 일종의 갔다 :) C++ 작품 – vternal3