简体   繁体   English

访问struct元素。 是否可以像矢量一样访问?

[英]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 "." 当定义struct“str”时,我们可以使用opertor“。”访问每个元素。 followed by the name of the element. 后跟元素的名称。 For instance "str.c" will give us the number 3. 例如,“str.c”将给出数字3。

However in this example we don't know the element of "str" to output when programing because it's randomly selected by sel. 但是在这个例子中,我们不知道编程时输出的“str”元素,因为它是由sel随机选择的。

I don't know how to output "str.???" 我不知道如何输出“str。???” from sel number, that is, str.a if sel=0, str.b if sel=1, and str.c if sel=3. 来自sel number,即,如果sel = 0,str.a,如果sel = 1,则str.b,如果sel = 3,则str.c.

I tried something like "str.[sel]", but it didn't work. 我尝试了类似“str。[sel]”的东西,但它没有用。 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. PD:我不想太烦,但是如何解决同样的问题,但现在假设a,b和c有不同的变量类型。 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. 如果有时想要按名称引用元素,有时需要按位置引用元素,请为结构定义operator []( int )

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: 你甚至可以使用int来分配,因为它是通过引用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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