#include #include //for the iomanipulator setw #include #include //for class string using namespace std; int n {10}; //at most n-1 people can be on line simultaneously int f(int i); //The function declaration announces the name of the function. //if f(vp + 1) == qp, the queue is empty. //if f(qp) == vp, the queue is full. int main() { string a[n]; //The queue is stored in an array of n strings. int qp {0}; //"queue pointer": subscript of 1st unoccupied element int vp {n-1}; //"vacated pointer": subscript of most recently freed el cout << "Type a name (one word) to put that person on line.\n" << "Type serve to serve the one who's been waiting longest.\n" << "Type list to print the queue.\n" << "Type exit to exit the program.\n"; for (;;) { //Infinite loop, until we break out below. cout << "\nGo ahead: "; string word; cin >> word; if (word == "exit") { cout << "Goodbye.\n"; break; //out of the for loop. } else if (word == "list") { int j {1}; //number the people who are waiting for (int i {f(vp+1)}; i != qp; i = f(++i)) { cout << setw(2) << j << " " << a[i]; if (f(vp + 2) != qp) { //queue contains > 1 if (i == f(vp+1)) { cout << " (oldest)"; } else if (i == f(qp - 1)) { cout << " (newest)"; } } ++j; cout << "\n"; } } else if (word == "serve") { if (f(vp + 1) == qp) { cerr << "Sorry, the queue is already empty.\n"; } else { cout << "Serving " << a[f(vp + 1)] << ".\n"; vp = f(++vp); //End by making the queue smaller. } } else { //If none of the above, assume the word is a name. if (f(qp) == vp) { cerr << "Sorry, the queue aleady contains " << n-1 << " people.\n"; } else { qp = f(++qp); //Begin by making the queue bigger. cout << "Puting " << word << " online.\n"; a[f(qp-1)] = word; } } } return EXIT_SUCCESS; //Arrive here when the user types exit. } //This function takes an arbitrary integer i of any size, positive or negative, //and returns an integer in the range 0 to n-1 inclusive. //It would be legal to use this number i as a subscript in the array a. int f(int i) //The function definition creates the function. { i %= n; //means i = i % n if (i < 0) { //If i is negative, i += n; //make it non-negative. } return i; }