对结构元素的访问.有没有可能像矢量一样访问

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

本文关键字:访问 一样 有可能 元素 结构      更新时间:2023-10-16

我有下面的例子(简化)使用结构体:

#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.           
 }

定义了结构体"str"后,可以使用操作符"."后跟元素名来访问每个元素。例如"str.c"会给我们数字3。

然而,在这个例子中,我们不知道"str"的元素在编程时输出,因为它是随机选择的。

我不知道如何从sel number输出"str.??",即如果sel=0,则str.a,如果sel=1,则str.b,如果sel=3,则str.c。

我尝试了像"str.[sel]"这样的东西,但它不起作用。你能帮我吗?

PD:我不想麻烦太多,但如何解决同样的问题,但现在假设a,b和c有不同的变量类型。例如:

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

我尝试用两个操作符来做,但由于它们被重载而无法编译。

如前所述,如果不提供特定的映射和索引操作符,就无法做到这一点。下面的代码应该可以很好地工作:

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

一般来说,没有。

如果结构体中元素的唯一区别是它们的索引,则在该结构体中定义vector或数组。

如果您有时想通过名称引用元素,有时又想通过位置引用元素,请为该结构定义一个operator []( int )

如果你的结构中只有两个int型,最简单的方法是:

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

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

,你甚至可以用int来赋值,因为它是通过引用的:

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