如何通过引用传递二进制搜索 C++ 的结构

how to pass by reference a struct for binary search C++

#include <iostream>
#include <fstream>
using namespace std;

typedef struct student
{
    char name[30];
    char surname[50];
    int AM;
    int age;
}st;

int binsearch(st *s, int left, int right, int x) // the program crashes when i try to do the search                     
{
    while (left <= right)
    {
        int middle = (left +right) / 2;
        if (s[middle].AM == x)
            return middle;
        else if (x > s[middle].AM)
            left = middle + 1;
        else
            right = middle - 1;
    }
    return -1;
}

int main ()
{
    int ap,flag=1,n,i=0;

    st *s;
    while(ap != 0)
    {
       cout << "\n1. Create array" << endl;
       cout << "2. Print the array" << endl;
       cout << "3. Binary Search " << endl;
       cout << "0. Exit" << endl;
       cout << "Please give an answer ";
       cin >> ap;

       if (ap == 1)
       {

          ifstream file1("students.txt");
          if (!file1)
          {
          cout << "Unable to open file for reading.\n";
          return(1);
          }
          file1 >> n;
          s = new st[n];
          while (i < n)
          {
             file1 >> s[i].name  >> s[i].surname >> s[i].AM >> s[i].age;
             i++;
          }
          flag = 2;

       }
       if (ap == 2 && flag == 2)
       {
          for(i = 0; i < n; i++)
          {
              cout << s[i].name << " "  << s[i].surname << " " << s[i].AM << " " << s[i].age << " " << endl;
          }
       }
       if (ap == 3 && flag == 2)
       {
           int x, i, left = s[0].AM, right = s[n].AM, middle; // the error is somewhere here 

           cout << "Give the AM to search  "; // AM is a single number something like an ID number
           cin >> x;c 
           middle = binsearch(s, left, right, x);
           if(middle != -1)
           {
               cout << "We have found the student !" << endl;
           }
           else
           {
               cout << "We didn't find the student  %d" << x << endl;
           }

       }
    };
    delete[] s;
    return 0;
}

我想我在二进制搜索函数中传递了错误的类型。 我尝试将 int right 和 int left 转为 st ,这是函数中的 struct student 我不知道下一步该怎么做。 任何帮助将不胜感激

s的有效索引应该是从0到n-1。所以 "right = s[n].AM" 正在尝试访问超出你分配的内存的末尾。

在您评论的行中,(int x, i, left = s[0].AM, right = s[n].AM, middle;) 应该是 s[n-1] .AM 因为大小为 n 的数组的索引仅从 0 到 n-1。

int x, i, left = s[0].AM, right = s[n].AM, middle; // the error is somewhere here

这里有几个变化:

  • 无需再次声明变量 i,如果您出于某种目的需要该变量,请考虑更改其名称。

  • s[n]应该是s[n-1]