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

时间:2016-02-01 01:19:47

标签: c++ if-statement break binary-search

我有一个工作二进制搜索功能,要求用户输入一个名称,它将在学生数组结构中搜索它,并显示该学生的相应平均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);
}

5 个答案:

答案 0 :(得分:1)

将您while的{​​{1}}循环放在自己的独立函数中。

现在,breakreturn;具有相同的效果。

答案 1 :(得分:1)

在你的循环中引入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; } ... }

{{1}}

答案 2 :(得分:0)

这是我想的一个工作

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 ;
    }
 }
}

答案 3 :(得分:0)

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

....
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

答案 4 :(得分:0)

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

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

pointless: ;

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