【发布时间】:2016-01-20 14:43:26
【问题描述】:
#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
我不知道下一步该做什么。
任何帮助将不胜感激
【问题讨论】:
-
因为 bin 搜索是有几个“逐个”的算法,最简单的方法是检查一些已经实现的。这是我通常复制的内容:lxr.free-electrons.com/source/lib/bsearch.c(通过发布此内容,我并不是说“复制代码”,而是逐行检查并使用它只是为了避免“关闭一个”错误。
-
您的代码几乎不是 C++。摆脱那些指针,使用
std::string并忘记 C 中的typedef struct技巧。 -
这不是 C++ !!!!!!另外,与 C 不同的是,C++ 中的引用传递不是通过指针传递的。C++ 有一个不同的实体,称为引用。你的代码需要大量修改!!!
-
你在谈论哪个传递引用?清楚
标签: c++ struct binary parameter-passing pass-by-reference