2

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;
        }
2
  • 3
    c++ has no reflection you cannot iterate members of a type. unless you do put them inside an array of course Commented Sep 8, 2020 at 17:39
  • 1
    I appreciate that you are forthcoming about not knowing the right terms for things and took a reasonable shot at describing what you want even though you don't know how to do it. I realize it's difficult to ask questions like this when you don't know what you're looking for. But as a word of advice, don't let the code speak entirely for itself. Describe, in words, what you are trying to accomplish and what you are hoping your results to be. Commented Sep 8, 2020 at 17:52

1 Answer 1

3

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";
}

Godbolt link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.