通过函数参数确定结构体成员
Determine the struct member through function parameter
我想创建一个函数,它将分配结构数组的值,并通过其参数确定结构体的成员。
我的意思是,与其为结构的每个成员创建单独的函数,不如通过函数参数确定成员(示例:&.tests,课程.exams)
写下的代码 ı 仅用于解释我的意思,值可以从文本文件中导入,而不是随机分配它们。
我想了解的是;有没有其他方法可以在不写其名称的情况下调用结构成员?
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct lsn
{
char name[20];
int tests[4];
int quizzes[4];
int exams[4];
int finals[4];
};
void random_notes(lsn *x, int *y)
{
int i,j;
for(i=0;i<20;i++)
for(j=0;j<4;j++);
x[i].y[j]=rand()%101;
}
int main()
{
srand(time(NULL));
lsn lessons[30];
random_notes(lessons, &.tests);
random_notes(lessons, &.quizzes);
random_notes(lessons, &.exams);
random_notes(lessons, &.finals);
return 0;
}
而不是创建 4 个函数如下,
void random_tests(lsn *x)
{
int i,j;
for(i=0;i<20;i++)
for(j=0;j<4;j++);
x[i].tests[j]=rand()%101;
}
void random_quizzes(lsn *x)
{
int i,j;
for(i=0;i<20;i++)
for(j=0;j<4;j++);
x[i].quizzes[j]=rand()%101;
}
void random_exams(lsn *x)
{
int i,j;
for(i=0;i<20;i++)
for(j=0;j<4;j++);
x[i].exams[j]=rand()%101;
}
void random_finals(lsn *x)
{
int i,j;
for(i=0;i<20;i++)
for(j=0;j<4;j++);
x[i].finals[j]=rand()%101;
}
只有一个通过其参数确定结构成员的函数,
void random_notes(lsn *x, .struct_member y)
{
int i,j;
for(i=0;i<20;i++)
for(j=0;j<4;j++);
x[i].y[j]=rand()%101;
}
在这个例子中,函数非常小,但想象一个函数中一个巨大的代码,只有结构体成员不同,其余代码是相同的。
是的,C++有一个"指向成员的指针"的概念。这将允许您传递要初始化的成员的身份。但是语法有点不稳定,所以要小心:
void random_notes(lsn *x, int (lsn::* y)[4])
{
int i,j;
for(i=0;i<20;i++)
for(j=0;j<4;j++);
(x[i].*y)[j]=rand()%101; // << Access the member of x[i] via y
}
这是这样称呼的:
random_notes(lessons, &lsn::tests);
传递一个函数,该函数在调用时返回相应的结构成员。例如:
random_notes(lessons, [=](lsn& lesson) { return lesson.quizzes; });
在random_notes
函数中,您只需使用 lsn
实例调用该函数,它就会为您提供要填充的数组
相关文章:
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 如何获取结构体成员的地址
- 访问不同类的私有结构体成员
- C++ 使用成员函数返回结构体指针属性的值
- 通过函数参数确定结构体成员
- 如何使用其他函数返回的值为结构体成员赋值
- 当我想为结构体声明新成员时,有些麻烦我不明白
- CUDA:结构体的共享数据成员和对该结构体的引用成员具有不同的地址和值
- 按结构体的特定成员对结构体数组进行排序
- 如何在编译时输出结构体中成员的偏移量(C/ c++)
- Vector::erase()也擦除结构体的成员向量
- 模板结构体的静态const成员的不同值
- 比较值与结构体成员的问题
- 从二进制文件中提取结构体成员
- 为什么我的结构体成员没有使用"{}"正确初始化?
- 函数参数 -> 结构体成员的 void* 和常量 void* 的解决方案
- 动态结构体成员在使用 CUDA/NVCC 传递到函数时损坏
- 将相同的变量赋给具有不同值的多个结构体成员
- 为什么编译器不能像变量声明那样在结构体成员中设置 char[] = { .. } 的大小?