你的代码是通过 tmp.stu_name.find(value, pos) != string::npos 进行模糊查找,其中 tmp 是一个 student 对象,value 是输入的名字搜索关键字。在这个表达式中,find() 函数会返回查询子字符串 value 在 tmp.stu_name 中首次出现的位置。如果查询到了该子字符串,则会返回该位置的索引值;否则返回 string::npos。
下面是修改后的代码实现模糊查询修改代码如下
修改后的代码如下:
void Student::Mfind(){
student tmp;
string::size_type pos = 0;
string value;
cout << "请输入要查找的部分:";
cin >> value;
while(1){
if (tmp.stu_name.find(value, pos) != string::npos || tmp.stu_id.find(value, pos) != string::npos
|| tmp.stu_birth.find(value, pos) != string::npos || tmp.stu_department.find(value, pos) != string::npos
|| tmp.stumajor.find(value, pos) != string::npos || tmp.stu_class.find(value, pos) != string::npos
|| tmp.stu_tel.find(value, pos) != string::npos || tmp.stu_email.find(value, pos) != string::npos ) {
cout << "学号:" << tmp.stu_id << " 姓名:" << tmp.stu_name << " 年龄:" << tmp.stu_age
<< " 性别:" << tmp.stu_sex << " 籍贯:" << tmp.stu_birth << " 系别:" << tmp.stu_department << endl;
cout << "专业:" << tmp.stumajor << " 班级:" << tmp.stu_class << " 手机:" << tmp.stu_tel
<< " Email:" << tmp.stu_email << endl;
}
pos++;
if (pos >= tmp.stu_name.length()) break;
}
}
在原有代码基础上,增加了在各个属性中查找目标字符串的条件判断,以达到模糊匹配的效果。同时将查找条件中的姓名、年龄、性别等属性的输出进行了格式化。
修改后,通过使用for循环遍历当前存储的所有学生信息。使用find方法检查每个学生姓名中是否包含用户输入的关键字value,如果包含则输出该学生信息。这样就实现了模糊查询。
template <class ElemType>
int Equivalence<ElemType>::Find(ElemType e) const
// 操作结果:查找结点p所在树的根
{
int i,k,p = 0;
while (p < size && set[p].data != e) //遍历寻e
p++;
if (p == size) //如果是因为寻完而退出
throw Error("元素不存在!"); // 抛出异常,表示元素并不在集中
//否则说明元素是存在集合中的,并且此时set[p]存的就是元素e
for(i=p;set[i].parent>=0;i=set[i].parent) //从p开始向上找p的根节点的序号i
; //找到就OK,不用多做什么,至此i已经找到,树的重构尚未执行
//重构过程
if(p!=i) //p不是根
{
while(i!=set[p].parent) //从p开始向上逐层压缩(变化的p指示着要修剪重构的节点)
{
k=set[p].parent; //用局部自动变量k记录这个p的双亲,为的是一次重构后还能把p指向向上的双亲继续执行
set[p].parent=i; //直接改变其双亲为根节点i就可以了,因为重构过程总元素数目没变,i是不用动的
p=k; //把双亲还给p,为p的下一次执行做好准备
}
}
return i;
}
今天老师指出了一些问题,我又改了一下更新了这篇文章。
我可以为您提供如下解决方案:
在学生信息管理系统中实现模糊查询功能需要进行如下步骤:
以下是基于数组进行数据存储的代码实现:
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100
struct Student {
char name[20];
char sex[5];
int age;
char hometown[20];
};
int main() {
struct Student students[MAX_STUDENTS] = {
{"Tom", "Male", 18, "Beijing"},
{"Lucy", "Female", 19, "Guangdong"},
{"Alex", "Male", 20, "Shanghai"},
{"Alice", "Female", 21, "Guangxi"},
{"Bob", "Male", 22, "Sichuan"}
};
int count = 5;
char keyword[20];
printf("Please input keyword for searching: ");
scanf("%s", keyword);
for (int i = 0; i < count; i++) {
if (strstr(students[i].name, keyword) != NULL
|| strstr(students[i].hometown, keyword) != NULL) {
printf("%s %s %d %s\n", students[i].name, students[i].sex,
students[i].age, students[i].hometown);
}
}
return 0;
}
以上代码实现了基于数组的模糊查询功能,用户可以输入关键字,程序会遍历数组中的所有学生信息,针对姓名和籍贯两个字段进行模糊匹配查找,并将符合条件的学生信息进行输出展示。
如果需要实现基于链表的模糊查询功能,可以参考参考资料中给出的链表相关代码实现方式进行改进。