简体   繁体   中英

Access to the struct elements. Is it possible to access like a vector?

I have the following example (simplified) using a struct:

#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;

struct s_str
{
    int a=1,b=2,c=3;
};

int main(void)
{
    s_str str;
    int sel;    
    srand(time(NULL));                 //initialize random seed
    sel = rand() % (3);                //generate a random number between 0 and 2

    cout << "sel: " << sel << endl;     
    cout << "str: " << str.??? << endl;//I was wondering to output a, b or c 
    return 0;                          //depending whether sel=0,1,2respectively.           
 }

When the struct "str" is defined, we can access to each element by using the opertor "." followed by the name of the element. For instance "str.c" will give us the number 3.

However in this example we don't know the element of "str" to output when programing because it's randomly selected by sel.

I don't know how to output "str.???" from sel number, that is, str.a if sel=0, str.b if sel=1, and str.c if sel=3.

I tried something like "str.[sel]", but it didn't work. Can you help me?

PD: I don't want to bother too much, but how to solve the same problem but now supposing that a,b and c have different variable type. For example:

int a=1,b=2;
string c="hola";  

I tried to do it with two operators, but it didn't compile because they were overloaded.

As mentioned you can't do this without providing a certain mapping and indexing operator. The following should work well :

struct s_str
{
    int a=1,b=2,c=3;
    int& operator[](int index) {
        switch(index) {
            case 0:
                return a;
            case 1:
                return b;
            case 2:
                return c;
            default:
                throw std::out_of_range("s_str: Index out of range.");
            break;
        }   
    }
};

int main() {
    s_str s;
    cout << s[0] << ", " << s[1] << ", " << s[2] << endl;
    // cout << s[42] << endl; // Uncomment to see it fail.
    return 0;
}

In general, no.

If the only distinguishing feature of the elements of the struct is their index, define a vector or array in the struct.

If you sometimes want to refer to the elements by name and sometimes by position, define an operator []( int ) for the struct.

Te easiest way, if you have only a couple of ints in your structure is:

struct s_str
{
    int a = 1, b = 2, c = 3;
    int& operator[] (size_t t) {
        assert(t<3); // assumption for the following to return a meaningful value
        return (t == 0 ? a : (t == 1 ? b : c));
    }
};

You'd access with

   cout << "str: " << str[sel] << endl;

and you could even use int to assign, because it's by reference:

str[sel] = 9; 
cout << "a,b,c=" << str.a << "," << str.b << "," << str.c << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM