对结构元素的访问.有没有可能像矢量一样访问
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.
}
定义了结构体"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;
相关文章:
- 通过方法访问结构
- 访问数据成员(本身是对象)的数据成员,就好像它们是类成员一样
- 访问另一个类(系统)的非静态字段,就好像它是我自己的字段一样 - 优雅地
- 使更长的 std::array 可访问,就好像它更短一样
- 在C 中,可以用语法[i,j,..]实现访问数组元素的功能,而语法就像numpy中的ndarray样式一样
- 我是否可以像访问自己的对象一样访问对象的'base part'?
- 我需要一个像堆栈一样的数据结构,但具有随机访问,但是,我应该实现什么
- 函数来像访问向量一样访问向量中结构的元素
- 如何创建文件路径可以像磁盘一样访问的虚拟文件系统
- 使QTableWidget可逐行编辑,就像MS访问一样
- 那么,是否可以像使用指针一样使用迭代器访问二维向量中的所有元素呢?
- 对结构元素的访问.有没有可能像矢量一样访问
- 需要学习如何通过指针正确访问实例变量"this"就像在 Java 中一样
- 如何像访问数组一样访问Tuple(具有括号重载和类型安全)
- 像访问文件流一样访问内存块(/ C/ c++数组)
- 像数组一样访问指针
- 像数组一样访问std::map的std::映射
- 是否可以像重载另一种类型的成员访问运算符一样解析静态成员
- 像访问数组一样访问c++队列元素
- 如何像直接访问文件一样使用内存:类似于read和fwrite函数