首页 > 解决方案 > 使用二进制搜索打印在结构向量中找到的大量值

问题描述

我得到了以下结构:

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没有产品具有插入的价格。(因此它确实知道何时有符合标准的产品,但它不会打印它们)。非常感谢您!

标签: c++data-structuresstructbinary-search

解决方案


推荐阅读