1

Let's say I have 15-20 float variables that are included in a Person class. Each of those float variables are counting something different (e.g : var_0 : count_cats, var_1 = count_dogs, ..., var_19 = count_X).

I currently have those variables in a class like this :

class Person {
double count_cats;
double count_dogs;
etc...
}

I would like to know if there is a way I could put those variables in a kind of container where I could iterate over all of them when needed, but where I could still access the variables by their names (I don't want to have a vector<double> vec_count and have vec_count[0] representing count_cats, vec_count[1] representing count_dogs, etc.)

Thanks !

Phil_QC
  • 11
  • 1
  • 1

1 Answers1

0

So you want an iterable data structure where you can also pull out values by referencing their names...you're thinking about an std::map!

Here you can do:

std::map<std::string, double> counts;
counts["cats"] = 5;
counts["dogs"] = 77;

for( auto it = counts.begin(); it != counts.end(); it++) {
    std::cout << "There are " << it->second << ' ' << it->first << std::endl;
}

See a live example here (ideone).

scohe001
  • 15,110
  • 2
  • 31
  • 51