gpt4 book ai didi

c++ - 帮助实现结构数组中名称的二进制搜索

转载 作者:行者123 更新时间:2023-11-30 04:34:56 24 4
gpt4 key购买 nike

我需要使用二进制搜索在结构数组中查找请求的名称。我使用了二进制搜索示例代码来搜索整数并修改它以搜索数组索引以比较每个结构中的名称。该程序运行但从未找到该名称,因此肯定是某处出了问题。不确定这是我从流中获取名称的方式,还是只是我一般搜索的实现方式。任何人都可以看看提供一些反馈吗?谢谢

输入函数的相关代码:

char entryName[31];
char discard;
string entryNameString;

cout << "What is the name of the entry you would like to look up?" << endl;
cin >> entryNameString;
cin.get(entryName, 30);
cin.get(discard);
findName(listLength, arrayOfStructs, entryName);

二分查找函数:

void findName(int listLength, contactInfo* arrayOfStructs, const char* entryName)
{
bool found = false;
int low = 0, high = listLength-1, mid;

while (!found && low <= high)
{
mid = (low + high) / 2;
if (strcmp(entryName, arrayOfStructs[mid].contactName) == 0)
found = true;
else
if (strcmp(entryName, arrayOfStructs[mid].contactName) < 0)
high = mid - 1;
else
low = mid + 1;
}

if (found)
{
cout << arrayOfStructs[mid].contactName << endl;
cout << arrayOfStructs[mid].birthday << endl;
cout << arrayOfStructs[mid].addressInfo.streetName << endl;
cout << arrayOfStructs[mid].addressInfo.cityName << endl;
cout << arrayOfStructs[mid].addressInfo.state << " ";
cout << arrayOfStructs[mid].addressInfo.zipcode << " ";
cout << arrayOfStructs[mid].addressInfo.phoneNumber << endl;
cout << arrayOfStructs[mid].typeOfentry << endl;
}
else
cout << "NOT FOUND" << endl;
}

编辑:arrayOfstructs[].contactName 按字母顺序排列,(例如 .contactName = Amanda,位于比 .contactName = Zorak 更小的索引中)

最佳答案

如果您尝试输入由空格分隔的名称,您需要使用 std::getline而不是 istream::operator>>

关于c++ - 帮助实现结构数组中名称的二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5678337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com