【发布时间】:2019-08-15 01:24:21
【问题描述】:
我正在开发一个电话簿程序。我需要使用 findContact 函数返回的位置并将其用作 deleteContact 函数中的索引。
void AddressBook::deleteContact(std::string nameMatch) //need to implement find contact && not found if there is a space at end of name
{
if (length == 0)
{
std::cout << "Phonebook is empty" << std::endl;
return;
}
findContact(nameMatch);
std::cout << phoneBook[position]->name << " deleted" << std::endl;
phoneBook[position] = phoneBook[length - 1]; //how to use position
length--;
return;
}
我使用二分搜索,因为它是由我的教授指导的。
int AddressBook::findContact(std::string nameMatch)
{
int first = 0;
int last = length - 1;
int middle;
int position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (phoneBook[middle]->name == nameMatch)
{
found = true;
position = middle;
}
else if (phoneBook[middle]->name > nameMatch)
{
last = middle - 1;
}
else
{
first = middle + 1;
}
}
return position;
}
它大多不完整,但我正在尝试弄清楚如何使用 position
从我的 findContact 函数返回并在我的 deleteContact 中使用它。
【问题讨论】: