STL binary_search()

时间:2017-10-06 19:01:35

标签: c++11 stl binary-search

我创建了一个struct目录,其中包含数据成员作为字符串名称和地址以及电话号码。我想使用STL c ++ binary_search()执行二进制搜索,以输入名称来显示信息。我的结构是结构数组。我已经按名称成功地对结构进行了排序。我如何搜索和显示?我没有得到语法。

    #include<iostream>
    #include<algorithm>
    #include<vector>
    #include<string.h>
    using namespace std;
    struct directory
    {
        string name;
        char address[50];
        long long int ph; 
        int pin;
    }d[10];
    bool compare(directory & lhs, directory & rhs)
    {
        if(lhs.name!=rhs.name)
        {
            return lhs.name < rhs.name;
        }
    }
    int main()
    {
        for(int i=0;i<10;i++)
        {
            cout<<"\nEnter name: ";
            cin>>d[i].name;
            cout<<"\nEnter Address:";
            cin.ignore();
            cin.getline(d[i].address,50);
            cout<<"\nEnter ph. no.: ";
            cin>>d[i].ph;
        }
        sort(d,d+10,&compare);
        for(int i=0;i<10;i++)
        {
            cout<<"\nName: "<<d[i].name;
            cout<<"\nAddress:"<<d[i].address;
            cout<<"\nPh. no.: "<<d[i].ph<<"\n";
        }
        string nam;
        cout<<"Enter the first name to search: ";
        cin>>nam;
        if(binary_search(d,d+10,nam,&compare));
        {
            cout<<d->name<<"\n";
            cout<<d->address<<"\n";
            cout<<d->ph<<"\n";
        }
        return 0;
    }

0 个答案:

没有答案