[英]Access to the struct elements. Is it possible to access like a vector?
我使用结构有以下示例(简化):
#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.
}
当定义struct“str”时,我们可以使用opertor“。”访问每个元素。 后跟元素的名称。 例如,“str.c”将给出数字3。
但是在这个例子中,我们不知道编程时输出的“str”元素,因为它是由sel随机选择的。
我不知道如何输出“str。???” 来自sel number,即,如果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;
}
一般来说,没有。
如果结构元素的唯一区别特征是它们的索引,则在结构中定义向量或数组。
如果有时想要按名称引用元素,有时需要按位置引用元素,请为结构定义operator []( 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.