Write data structure for dictionary.
1. Implement function for inserting a word into a dictionary.
2. Implement function for lookup in dictionary.
SOLUTION :
#include "iostream.h"
#include "cstdio"
#include "string.h"
#include "set.h"
#include "cstdlib"
using namespace std;
class dictionary
{
private:
set dict;
public:
bool insert(string);
bool lookup(string);
};
bool dictionary :: lookup(string s)
{
set <string> :: iterator it;
it=dict.find(s);
if(*it == s && it != dict.end())
{
return true;
}
else
{
return false;
}
}
bool dictionary :: insert(string s)
{
pair<set<string> :: iterator ,bool> ret;
ret=dict.insert(s);
return(ret.second);
}
int check_alpha(string s)
{
for(int i=0; i
{
if(isalpha(s[i]))
{
continue;
}
else
{
return 1;
}
}
return 0;
}
int main()
{
bool status;
string n_word ="";
string choice ="";
dictionary dict;
int flag=0;
int check=0;
while(true)
{
cout<<"\n\nSelect Choice : ";
cout<<"\n\n1. Insert\n"
<<"2. LookUp\n"
<<"3. Exit\n\n"
<<"Enter : ";
getline(cin,choice,'\n');
switch(choice[0])
{
case '1':
cout<<"\n\nEnter the word to be entered in the dictionary : ";
do
{
flag=0;
getline(cin,n_word,'\n');
cin.clear();
if(n_word.length() == 0)
{
flag=1;
cout<<"\n\n Empty String Not Allowed \n\n";
continue;
}
check=check_alpha(n_word);
if(check==1)
{
flag=1;
cout<<"\n\n Enter only Alphabets \n\n";
continue;
}
}while(flag==1);
status=dict.insert(n_word);
if(status == true)
{
cout<<"\nElement "<<n_word<<" is present in the dictionary\n\n";
}
else
{
cout<<"Element already Exists \n\n";
}
break;
case '2': cout<<"\n\nEnter the word to be searched in the dictionary : ";
do
{
flag=0;
getline(cin,n_word,'\n');
cin.clear();
if(n_word.length() == 0)
{
flag=1;
cout<<"\n\n Empty String Not Allowed \n\n";
continue;
}
check=check_alpha(n_word);
if(check==1)
{
flag=1;
cout<<"\n\n Enter only Alphabets \n\n";
continue;
}
}while(flag==1);
status=dict.lookup(n_word);
if(status == true)
{
cout<<"\nElement "<
}
else
{
cout<<"Element does not exist in it \n\n";
}
break;
case '3': exit(0);
break;
default: cout<<"\n\nEnter Correct Option \n\n";
}
}
}
No comments:
Post a Comment