[英]C++ Linear search algorithm on arrays
几周前,我开始使用C ++进行编程。 我正在开发一个将用户输入数据存储到数组列表中的应用程序。 输入用户数据时,应用程序必须能够检查用户是否已存在于阵列列表中。 该程序无法存储用户输入或无法检查用户是否已存在于阵列列表中。
int linearSearch(int array[], int size, int searchValue)
{
for (int i = 0; i < size; i++)
{
if (searchValue == array[i])
{
return i;
break;
}
}
return -1;
}
void customerReg(){
const int Capacity = 99;
int cnic[Capacity];
int customerNic;
int search = 0;
cout << "Enter Customer NIC: \n";
cin >> cnic[Capacity];
search = linearSearch(cnic, Capacity, customerNic);
if (search != -1){
cout << "Customer is already registered!\n";
}
else {
string customerName;
cout << "Enter Customer Name: \n";
cin >> customerName;
}
关于什么:
...
cout << "Enter Customer NIC: \n";
cin >> customerNic; // <=== instead of: cnic[Capacity];
其他说明:
cnic[]
未初始化 cnic[]
,这是该函数的局部方式,一旦您从函数返回就将丢失。 cnic
,跟踪表中注册的客户数量可能很有意义。 我假设您不能使用矢量或地图进行锻炼,并且您在学习之初就是对的。
因此,我假设customerReg()
是您正在使用的第一个函数,并且其他函数将跟随(显示,删除,修改...)。 在这种情况下,您必须将客户数据保留在功能之外:
const int Capacity = 99;
int cnic[Capacity] {};
int customer_count=0; // counter to the last customer inserted
然后,在customerReg()
,应使用客户数而不是最大Capacity
来调用搜索功能:
search = linearSearch(cnic, customer_count, customerNic);
稍后,在else
分支中,您必须将新的id插入到数组中:
else {
if (customer_count==Capacity) {
cout << "Oops ! Reached max capacity"<<endl;
else {
string customerName;
cout << "Enter Customer Name: \n";
cin >> customerName;
...
cnic[customer_count] = customerNic; // here you store the id
... // store (I don't know where) the other customer elements you've asked for
customer_count++; // increment the number of users that are stored.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.