CareerCup 3.7

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-in LinkedList 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值