Hierarchical data in C

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

How can I handle data in C++ like in newer dynamic languages, for example the arrays in PHP are quite neat:

$arr = array(

"somedata" => "Hello, yo, me being a simple string",

"somearray" => array(6 => 5, 13 => 9, "a" => 42),

"simple_data_again" => 198792,

);

I am open to all suggestions.

Answers

If you know in advance what all kinds of values map is going to hold, then use boost::variant. Or else, use boost::any. With boost::any, you could later add entries with any type of value to the map.


  Example code with boost::variant:   

Creating a map:

typedef boost::variant<std::string, std::map<int, int>, int> MyVariantType;
std::map<std::string, MyVariantType> hash;

Adding entries:

hash["somedata"] = "Hello, yo, me being a simple string";
std::map<int, int> temp; 
temp[6] = 5; 
temp[13] = 9;
hash["somearray"] = temp;
hash["simple_data_again"] = 198792;

Retrieving values:

std::string s = boost::get<std::string>(hash["somedata"]);
int i = boost::get<int>(hash["simple_data_again"]);

As pointed out by @Matthieu M in the comments, the key-type of the map can be a boost::variant. This becomes possible because boost::variant provides a default operator< implementation providing the types within all provide it.


  Example code with boost::any:   

Creating a map:

std::map<std::string, boost::any> hash;

Adding entries:

hash["somedata"] = "Hello, yo, me being a simple string";
std::map<int, int> temp; 
temp[6] = 5; 
temp[13] = 9;
hash["somearray"] = temp;
hash["simple_data_again"] = 198792;

Retrieving values:

std::string s = boost::any_cast<std::string>(hash["somedata"]);
int i = boost::any_cast<int>(hash["simple_data_again"]);

Thus, with help of boost::any the value-type in your map can be dynamic (sort of). The key-type is still static, and I don t know of any way how to make it dynamic.


  A word of advice:    

C++ is a statically typed language. The idioms like the one in your post which are used quite often in dynamic language don t fit well with the C++ language. Going against the grain of a language is a recipe for pain.

Therefore I d advise you not to try to emulate the idioms from your favorite dynamic languages in C++. Instead learn the C++ ways to do things, and try to apply them to your specific problem.


  References:   

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/3690276/hierarchical-data-in-c

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils