有没有办法解决使用 break 语句的问题?

Is there a way to work around using a break statement?

我有一个有效的二进制搜索功能,它要求用户输入一个名字,它会在学生数组结构中搜索它并显示该学生相应的平均 GPA。除非用户输入句点,否则它会一直循环让用户输入要搜索的名称。

我遇到的问题是我正在使用的 break 语句。我需要遵循的此功能的要求不允许我使用 break 语句。

但是,如果我删除 break 语句,我的二分查找将无限地打印出输出语句并且将不再正常工作。

有没有办法让我解决这个问题而不使用 break 语句?我有一种感觉,我可以使用多个 if 语句而不是 break 语句。

void binarySearch(Student* ptr, int MAXSIZE)
{
   string target;
   string period = ".";

   int first = 0,
   last = MAXSIZE - 1,
   mid;

  do
  {
    cout << "Enter student name (Enter . to stop): ";
    cin  >> target;

    while (first <= last)
    {
        mid = (first + last) / 2;
        if (ptr[mid].name.compare(target) == 0)
        {
            cout << "Student " << target << " :gpa " << ptr[mid].avg << endl;
            first = 0;
            last = MAXSIZE - 1;
            break; // I am stuck on making the binary search work without using this break statement
        }
        else if (ptr[mid].name.compare(target) < 0)
            last = mid - 1;
        else
            first = mid + 1;
    }
    if (first > last && target.compare(period) != 0)
    {
        cout << "This student was not found. Enter another name" << endl;
        first = 0;
        last = MAXSIZE - 1;
    }
  } while (target.compare(period) != 0);
}

将您 break 从中调用的 while 循环放在它自己的独立函数中。

现在,return; 将与 break; 具有相同的效果。

在你的循环中引入一个bool

bool nameFound = false;
while (first <= last && !nameFound)
{
    mid = (first + last) / 2;
    if (ptr[mid].name.compare(target) == 0)
    {
        cout << "Student " << target << " :gpa " << ptr[mid].avg << endl;
        first = 0;
        last = MAXSIZE - 1;
        nameFound= true;
    }
    ...
}

这是我认为的解决方法

do{

int ctr = 0;

while (first <= 0 && ctr ==0)
  {
   if (ptr[mid].name.compare(target) == 0)
    {
        cout << "Student " << target << " :gpa " << ptr[mid].avg << endl;
        first = 0;
        last = MAXSIZE - 1;
        ctr = 1 ;
    }
 }
}

只是文体评论(因为实际答案已经发布):如果您在需要之前设置必要的工作变量,而不是依靠各种退出情况来重置它们,则更可靠未来的迭代。即:

....
cin  >> target;

// Define and initialize right before they are needed.
int first = 0;
int last = MAXSIZE - 1;

while (first <= last) {
    int mid = (first + last) / 2; // Not needed outside the loop

一个简单的解决方案是将break替换为goto,并在while之后引入一个标签,例如:

do { 
   // ... 
   goto pointless;
   // ...
} while (bla);

pointless: ;

注意: 除了遵守您声明的不使用 break 的要求外,这在所有方面都比使用 break; 更糟糕。