I created a struct directory with data members as string name and address and phone no.s. I want to perform binary search using STL c++ binary_search() to display info by taking input as name. And my structure is array of structs. I have successfully sorted the structure by name.
#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;
}
Aucun commentaire:
Enregistrer un commentaire