C++ 数组上的线性搜索算法
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[]
,顺便说一下,这是函数的本地,一旦您从函数返回就会丢失。 - 根据您启动/填充
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.
}
}
相关文章:
- 向量上的线性搜索
- std::unordered_map 搜索算法是如何实现的?
- 二叉搜索如何比线性搜索更快?
- C++(线性搜索和排序)
- C++线性搜索算法,确定数组中元素的数量
- 如何在 c++ 中线性搜索两个数组?
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 变量未在此范围内声明 数组线性搜索
- 尝试实现二叉搜索算法,似乎无法使其工作
- 如何在 c++ 中对两个向量进行线性搜索?
- 线性搜索 MPI(在其他进程中停止)
- SIMD 线性搜索比展开循环慢
- 图上的深度优先搜索算法中的内存泄漏
- C++线性搜索算法
- 为什么排序调用比较函数的频率低于线性最小搜索算法
- 线性搜索算法
- C++ 数组上的线性搜索算法
- 如何创建一个线性搜索算法比我的教科书提供的更容易
- C++线性搜索算法