C++ 指向struct数组属性的数组指针
我有以下结构和主要功能:C++ 指向struct数组属性的数组指针,c++,arrays,pointers,struct,attributes,C++,Arrays,Pointers,Struct,Attributes,我有以下结构和主要功能: struct myStruct{ string name; int id; int group; }; int main(){ myStruct student[5]; // The struct student has an array of 5 elements search(student, 1, 33); // We pass the struct student with all the 5 elements }
struct myStruct{
string name;
int id;
int group;
};
int main(){
myStruct student[5]; // The struct student has an array of 5 elements
search(student, 1, 33); // We pass the struct student with all the 5 elements
}
我想将一个结构传递给函数搜索,然后生成一个数组指针,该指针存储某个属性的值,但存储结构的所有数组的值
*e指向student,所有数组(5),因此如果type等于1,指针将指向结构e的每个数组的属性的所有值
void search(myStruct *e, int type, int value){
if (type == 1) int *ptr[] = e[0]->id; //An int pointer because the id is an int
if (type == 2) int *ptr[] = e[0]->group;
for (int i = 0; i < 5; i++){
if(*ptr[i] == value){
cout << e[i]->name << endl;
cout << e[i]->id << endl;
cout << e[i]->group << endl;
}
}
}
void搜索(myStruct*e,int类型,int值){
if(type==1)int*ptr[]=e[0]->id;//一个int指针,因为id是int
if(type==2)int*ptr[]=e[0]->group;
对于(int i=0;i<5;i++){
如果(*ptr[i]==值){
cout name一种非常简单的方法,有点低级,只适用于属性为相同类型(例如int)并连续存储的POD struct类型
假设您的结构如下所示:
struct myStruct {
string name;
int attr1;
int attr2;
...
int attr8;
}
您可以按如下方式编写搜索函数:
void search(myStruct *e, int type, int value) {
int *ptr[5];
for (int i = 0; i < 5; ++i) {
int *base = &e[i].attr1; // treat attr1...attr8 as an int array
ptr[i] = &base[type - 1];
if (*ptr[i] == value) {
cout << e[i].name << endl;
for (int j = 0; j < 8; ++j) {
cout << base[j] << endl;
}
}
}
}
void搜索(myStruct*e,int类型,int值){
int*ptr[5];
对于(int i=0;i<5;++i){
int*base=&e[i].attr1;//将attr1…attr8视为int数组
ptr[i]=&base[type-1];
如果(*ptr[i]==值){
cout一种方法是制作一个“指向成员的指针”。注意:这不是一个指针数组,而是一个只能与类的对象一起使用的指针
还要注意:这是相当先进的,所以您可能希望首先在您的头脑中获得正常的指针
void search(myStruct *e, int type, int value) {
int myStruct::*ptr; // ptr is a pointer to a member variable of an object
if (type == 1) ptr = &myStruct::id;
if (type == 2) ptr = &myStruct::group;
for (int i = 0; i < 5; i++){
if (e[i].*ptr == value){ // access the value of the current object using ptr.
cout << e[i].name << endl; // Note that you had these accesses wrong.
cout << e[i].id << endl;
cout << e[i].group << endl;
}
}
}
void搜索(myStruct*e,int类型,int值){
int myStruct::*ptr;//ptr是指向对象的成员变量的指针
if(type==1)ptr=&myStruct::id;
if(type==2)ptr=&myStruct::group;
对于(int i=0;i<5;i++){
如果(e[i].*ptr==value){//使用ptr访问当前对象的值。
我不能理解这个问题。你提供的示例代码没有编译。student
不是“结构”。它最多是5个“结构”的数组。注意你的术语!