;)

Hey guys, I have another simple question today:

Lets say I have a structure:

struct Info{
    string name;
    string id;
    double telNum;
};
//....
Info person;
//....

Now, if I had a function in which I told it to output one of the elements in the structure, how would I go about doing this without doing something like the following:

void func(int i){
switch(!){
case 0:
//.... output name
case 1:
//.... output telnum
case 2:
//..... output ID
}
}

I'm wondering whether there was a way of doing this similar to the following:

void func(??? elem){
cout << person.[elem];
}

Hope you guys get the idea, thanks in advance.

The only way I know of (other than ways similar to the one already mentioned) is to create an array out of the data, and then you can access it with a number.

You could also create an accessor function, such as Info::getData(int data) that would do the same thing as already mentioned.

Any particular reason why you need to do this and not write separate accessor functions for each piece of data?

Just seeing if there were more convenient ways of achieving that. In the project I'm currently doing I was looking for a way to sort data and let the user choose what data (name, telephone, address, ...) to use as the base for sorting the structures.

I guess I'll have to copy and paste a bit for now.

;)

Hey guys,

Hi! :)

I have another simple question today:

Lets say I have a structure:

struct Info{
    string name;
    string id;
    double telNum;
};
//....
Info person;
//....

Now, if I had a function in which I told it to output one of the elements in the structure, how would I go about doing this without doing something like the following:

void func(int i){
switch(!){
case 0:
//.... output name
case 1:
//.... output telnum
case 2:
//..... output ID
}
}

I'm wondering whether there was a way of doing this similar to the following:

void func(??? elem){
cout << person.[elem];
}

Hope you guys get the idea, thanks in advance.

There are a few ways you can do this, like an overloaded indexer for the Info struct, but they don't really make much sense. Let's go at it a different way. Why are you trying to do this? It might be that you can solve your problem in a different way and get a better result out of it. :)

This article has been dead for over six months. Start a new discussion instead.