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;
}
本文介绍了一个动物收容所的管理系统,该系统基于“先进先出”原则,允许人们选择领养狗或猫,并遵循特定的数据结构和操作实现。

被折叠的 条评论
为什么被折叠?



