c++ - 使用二进制搜索打印在结构向量中找到的大量值
问题描述
我得到了以下结构:
struct data
{
string code;
string description;
float price;
};
用户在 中插入数据后data a[]
,程序应该查找并打印具有用户要求的价格的产品(使用二进制搜索)。
这是我写的(n是用户插入的产品数量):
void binary(int n, data a[])
{
int last = 0, first = n-1, med, p;
bool found = false;
cout<<"\nInsert the price of the products you'd like to see: ";
cin>>p;
while(last <= first && !found)
{
med = (last + first)/2;
if( a[med].price == p )
{
print(med, a);
found = true;
}
else if( a[med].price > p )
first = med - 1;
else
last = med + 1;
}
if(found)
{
int pos = med;
while(a[++pos].price == p)
{
print(pos, a);
}
while(a[--med].price == p)
{
print(pos, a);
}
}
else
cout<<"\nThere are no products that have the price you've inserted";
}
打印函数如下所示:
void print(int x, data a[])
{
cout<<"\nCode: " << a[x].code;
cout<<"\nDescription: " << a[x].description;
cout<<"\nPrice: " << a[x].price;
}
问题是它不打印任何东西,除非cout
没有产品具有插入的价格。(因此它确实知道何时有符合标准的产品,但它不会打印它们)。非常感谢您!
解决方案
推荐阅读
- r - 在嵌套的小标题中分组汇总(带有排列)
- kubernetes - 如何在 kubernetes 中按顺序在多个节点上运行 cronjob?
- php - 事务模式下的 CodeIgniter 与 PostgreSQL 和 PgBouncer
- flutter - Flutter:导航器在后退按钮上显示错误的页面
- python - Keras neural network with a set of data repeated over time
- r - 如何在 lmer for 循环中使可变权重动态化
- reactjs - Add plugin dayjs to next.config.js React.js Next.js
- excel - Excel PowerShell parse data from cell value
- python - Caching in multi process application
- python - How to formulate this integer constrained optimization over multiple variables in Scipy?