传递对象数组以进行搜索
Passing an array of objects for search
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class student
{ int rno;
char name[20];
float total;
public:
void In();
void Out();
void search(student ob[50],int,int);
int retrno()
{ return rno; //returns the roll no of student
}
};
void student::search(student ob[],int n,int srno)
{ int flag=0;
for(int i=0;i<n;++i)
if(ob[i].retrno()==srno) //checking for rollno match
{ flag=1;
cout<<"Student found";
ob[i].Out(); //calling Out() when match is found
}
if(flag==0)
cout<<"No matching records";
}
void student::In()
{ cout<<"Enter rno:";
cin>>rno;
cout<<"Enter name:";
gets(name);
cout<<"Enter total:";
cin>>total;
}
void student::Out()
{ cout<<"rno:";
cout<<rno;
cout<<"Name:";
puts(name);
cout<<"Total:";
cout<<total;
}
void main()
{ student ob[50];
int n,srno;
cout<<"Enter no. of students:";
cin>>n;
for(int i=0;i<n;++i)
ob[i].In(); //In() is called n times
cout<<"Enter rno to be searched:";
cin>>srno;
ob.search(ob,n,srno);
}
编译时出现 2 个错误。
11: Undefined structure 'student'
52: Structure required on left side of . or .*
我试图查看函数原型中是否有错误,但它看起来不错。我厌倦了没有数组大小的原型并获得了相同的错误。我也尝试全局初始化类,但遇到了同样的错误(我没有想法(。请帮我找到问题所在。
您的student
类代表一个学生,我认为搜索功能最好不要成为它的成员,考虑到您也向它传递了一个学生数组:
void search(student ob[], int n, int srno)
{
// ... keep your implementation
}
然后你可以用以下命令调用它:
search(ob,n,srno);
最好将输出部分分开,并使搜索函数仅返回指向找到(或未找到(元素的索引或指针。
我同意 Ulrich Eckhardt 关于所包含库的观点。
我想补充一点,您应该以某种方式检查用户输入的内容,我想记住这更正确使用:
int main() {
// ... stuff...
return 0;
}
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 如何在动态数组上使用搜索函数
- 在 C++ 中搜索动态分配的数组中的出现次数
- 当您在此单词中搜索单词时调整字符数组的大小?
- 在对象数组中搜索字符串并返回相应值的函数
- C++线性搜索算法,确定数组中元素的数量
- 递归二进制搜索与字符串数组
- 运行搜索数组
- 比较/搜索数组中多个整数的最佳解决方案
- C 搜索数组以获取一个数字,但如果找不到该数组,则不会触发其他语句
- 更高效的是,每次都读取文件或搜索数组中的数据
- 二叉搜索数组溢出 C++
- 在c++中搜索数组中的素数
- 性能问题C++ - 搜索数组
- C++搜索数组中最大的数字
- 我需要帮助创建一个可以搜索数组的函数
- 我想要一个递归函数来检查使用二进制搜索数组的顺序
- c#到c++的转换:搜索数组
- 搜索数组以查找单词的单独实例
- 搜索数组并比较它们