CareerCup 3.7

来源:互联网 发布:sift算法详解 编辑:程序博客网 时间:2024/05/21 17:04

3.7 An animal shelter holds only dogs and cats, and operates on a strictly "first in, first out" basis. People must adopt either the "oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such asenqueue,dequeueAny, dequeueDog, dequeueCat. You may use the built-inLinkedList data structure.

#include <iostream>#include <string>#include <queue>using namespace std;class Animal {private:    int order;protected:    string name;public:    Animal(const string &n) : name(n) {}    void setOrder(int ord) {        order = ord;    }    int getOrder() {        return order;    }    bool operator<(const Animal &a) {        return order < a.order;    }    virtual string type() {        return "animal";    }    virtual void print() {        cout << "animal: " << name << endl;    }};class Dog : public Animal {public:    Dog(const string &n) : Animal(n) {}    string type() {        return "dog";    }    void print() {        cout << "dog: " << name << endl;    }};class Cat : public Animal {public:    Cat(const string &n) : Animal(n) {}    string type() {        return "cat";    }    void print() {        cout << "cat: " << name << endl;    }};class AnimalQueue {private:    queue<Cat*> cats;    queue<Dog*> dogs;    int order;public:    AnimalQueue() {        order = 0;    }    void enqueue(Animal *a) {        a->setOrder(order++);        if (a->type() == "cat") {            cats.push(static_cast<Cat*>(a));        } else if (a->type() == "dog") {            dogs.push(static_cast<Dog*>(a));        }    }    Cat* dequeueCat() {        Cat *c = cats.front();        cats.pop();        return c;    }    Dog* dequeueDog() {        Dog *d = dogs.front();        dogs.pop();        return d;    }    Animal* dequeueAny() {        if (cats.empty()) {            return dequeueDog();        } else if (dogs.empty()) {            return dequeueCat();        }        if (*cats.front() < *dogs.front()) {            return dequeueCat();        } else {            return dequeueDog();        }    }};int main(){    AnimalQueue aq;    Cat *c1 = new Cat("c1");    aq.enqueue(c1);    Dog *d2 = new Dog("d2");    aq.enqueue(d2);    Animal *a = aq.dequeueAny();    a->print();    return 0;}

原创粉丝点击