有没有办法实现bsearch()
找到多个 key 实例。
例如:(obj*)bsearch(key=r,arr,elements,sizeof(obj),(int(*)(const void*, const void*)bcompare);
我目前编写的代码只能找到第一个实例,并且由于它的工作原理,无法继续找到第一个实例。
getline(target,81);
if(strcmp(target,"exit") == 0 || strcmp(target, "") == 0) break;
p = (Info*)bsearch(target,list,num,sizeof(Info),(int(*)(const void*, const void*))bcompare);
int foundIndex = (int)(p-list);
if(!p){
err_dis1_win();
clrscr();
}
else{
display_record(p);
cout << "\n\n found at index " << foundIndex << "\n";
getch();
clrscr();
}
变量:
- p - 是指向 Info 类对象的指针
- 目标- char 的 arr
- list - obj 的 arr
- foundIndex - 找到的元素的索引
- Info - 从基类派生的类
**比较功能
int bcompare(char *a,Info *b){
return(strncmpi(a, b -> get_name(), strlen(a)));
}
我不能使用其他方法,例如std::find
或编写自己的二进制搜索函数,必须使用bsearch()
我尝试了 else 块内的循环,以及使用变量 foundIndex 的比较函数,以及在通过 obj 列表 arr 循环的返回值上使用 while 循环。有没有办法从特定索引开始。我很感激任何帮助。我不是在寻找代码,而是在朝着正确的方向总体推进。谢谢你。
警告- 当前代码按预期编译和运行,但是我自己无法弄清楚我想要的功能。Google 和 Stackoverflow 上的搜索没有产生相关问题。