Hierarchical data in C ++

How can I process data in C ++, as in new dynamic languages, for example, arrays in PHP are pretty 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.

+3
source share
5 answers

If you know in advance that all types of values mapwill be held, use boost::variant. Or use boost::any. With the help of, boost::anyyou can subsequently add entries with any type of value to the map.


Sample code with boost::variant:

Map creation:

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;

Getting Values:

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

@Matthieu M , boost::variant. , boost::variant operator<, .


boost::any:

:

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

:

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;

:

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

, boost::any (). - , , .


:

++ - . , , , , ++. - .

++. ++ .


:

+4

, ++.

++ , , , , .

(, Boost.Any), - ?

/ , , , .

/ ++, ++ , PHP .

, , . ( ) .

+4

"" ++, .

+2

boost::variant " ", . , , :

std::map
<
 std::string,
 boost::variant
 <
  std::string,
  std::array<int, 4>,
  int
 >
> my_variant_array;

my_variant_array["somedata"] = "Hello, yo, me being a simple string";
my_variant_array["somearray"] = {
 1, 2, 3, 4
};
my_variant_array["simple_data_again"] = 198792;

You can even define a recursive change in such a structure containing another std::mapof boost::variant. Remember that this is something other than what you probably mean: boost::variant- it is a type of safe union of types with associated values. You can use it to implement a compiler for a dynamic language that allows you to create constructs according to your request. C ++ per se is not dynamic - everything must be strictly typed.

+1
source

Source: https://habr.com/ru/post/1764278/


All Articles