I want to write program that reads command from user, when d
is entered a taxi is entered ,it prompts to enter driver_id
and stores taxi in in queue (queue can have maximum n taxi), when command c
is entered by customer it assigns the earliest taxi in the queue to the customer.
I'm trying to solve it using struct member function so that our code looks good, but although I have initialized n=4
, it is only able to store 2
taxi, and shows me that the queue is full for the 3rd entry, which should not happen. Please review my approach.
Program run as such:
PS C:\Users; if ($?) { g++struct_taxi};; if ($?) { .\struct_taxi}
enter command:d
enter driverid:122
enter command:d
enter driverid:124
enter command:d
enter driverid:126
Q is full
Code:
#include<iostream>
using namespace std;
const int n=4;
struct Queue{
int elements[n],nwaiting,front;
void initialize(){
nwaiting=0;
front=0;
}
bool insert(int v){
if(nwaiting>=n)
return false;
elements[(front+nwaiting)%n]=v;
nwaiting++;
return true;
}
bool remove(int &v){
if(nwaiting==0)
return false;
else{
v=elements[front];
front=(front+1)%n;
nwaiting--;
return true;
}
}
};
int main(){
Queue q;
q.initialize();
while(true){
cout<<"enter command:";
char c;cin>>c;
if(c=='d'){
cout<<"enter driverid:";
int driverid;cin>>driverid;
if(!q.insert(driverid)){
cout<<"Q is full\n";}
else{
q.insert(driverid);
}
}
else if(c=='c'){
int driverid;
if(!q.remove(driverid)){
cout<<"No taxi available.\n";
}
else
//q.remove(driverid);
cout<<"assigning:"<<" "<<driverid<<endl;
}
}
}