Reputation: 35
in a Project of mine i need to call a member/property (dont know the right term) of a struct by a string which is inside an array.
The fat part in the line with the comment //???? is the Problem users[i].members[j] is nonsense and i know that but i just cant figure out what would be right there.
Thanks for your help in advance :D
struct person { // Eigenschaften des Eintrags
string name; //nachname
string vorname; //vorname
string telefon; // telfonnummer
};
const int numbr_struct_att = 3;
const string members[numbr_struct_att] = { "name","vorname","telefon" };
cout << setw(5) << left << "Index" << setw(20) << left << "Name" << setw(20) << left << "Vorname" << setw(20) << left << "Telefon" << endl; // Header
for (int i = 0; i <= usernum; i++) {
cout << setw(5) << left << i+1;
for (int j = 0; j < numbr_struct_att; j++) {
cout << setw(20) << left << users[i].members[j] // ?????
}
cout << endl;
}
Upvotes: 2
Views: 121
Reputation: 141200
Create a map of strings to member pointers.
#include <map>
#include <string>
#include <iostream>
struct person { // Eigenschaften des Eintrags
std::string name; //nachname
std::string vorname; //vorname
std::string telefon; // telfonnummer
};
// map names of variables to person member pointers to strings
std::map<std::string, std::string person::*> somemap{
{ "name", &person::name },
{ "vorname", &person::vorname },
};
// then just get the member pointers and call it on a instance of a person:
int main() {
person myperson{"my name"};
std::string I_choose_you = "name";
std::string persons_name = myperson.*somemap.find(I_choose_you)->second;
std::cout << persons_name << "\n";
}
Upvotes: 3