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;}
- CareerCup 3.7
- CareerCup 1.3
- CareerCup 1.4
- CareerCup 5.7
- CareerCup 14.6
- CareerCup 1.1
- CareerCup 1.2
- CareerCup 1.3
- CareerCup 1.4
- CareerCup 1.5
- CareerCup 1.6
- CareerCup 1.7
- CareerCup 1.8
- CareerCup 2.1
- CareerCup 2.2
- CareerCup 2.3
- CareerCup 2.4
- CareerCup 2.5
- 研发漫画之五:一切尽不在掌握,文山会海,累死我了
- Android 应用启动出现两个进程,多次退出,home 键重新进入程序
- ArcGIS for Server 10.2 新功能-站点备份和恢复
- 解决[__NSArrayM objectAtIndex:]: index 0 beyon Objective-C异常Bug方法
- android头像设置:从本地照片库或拍照获取并剪裁
- CareerCup 3.7
- 为Zend Studio (Eclipse)安装Spket插件,以支持ExtJS 4.0代码自动提示
- 用户需求、功能需求与业务需求的区别
- Linux下安装jdk1.7、tomcat7.0、mysql5.6
- 什么是NoSql?
- explain plan
- Web 开发人员需知的 Web 缓存知识
- mongoDB入门必读(概念与实战并重)
- CentOS 6安裝VNC、Xfce桌面、Firefox、Flashplayer教程Vagex挂机网赚