C++ 数组上的线性搜索算法

C++ Linear search algorithm on arrays

本文关键字:线性 搜索算法 数组 C++      更新时间:2023-10-16

几周前我就开始用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[],顺便说一下,这是函数的本地,一旦您从函数返回就会丢失。
  • 根据您启动/填充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. 
    }
}