《Cracking the Coding Interview》——第8章:面向对象设计——题目4

2014-04-23 18:17

题目:设计一个停车位的类。

解法:停车位,就要有停车、取车的功能了。另外我还加了一个工作线程用于计费,每秒给那些有车的车位加1块钱费用。

代码:

 1 // 8.4 Design a class to simulate the parking lot.

 2 #include <iostream>

 3 #include <string>

 4 #include <thread>

 5 #include <vector>

 6 using namespace std;

 7 

 8 class ParkingLot {

 9 public:

10     ParkingLot(int _capacity = 0):capacity(_capacity) {

11         slots.resize(capacity);

12         fees.resize(capacity);

13         fill(slots.begin(), slots.end(), false);

14         fill(fees.begin(), fees.end(), 0);

15     };

16     

17     void start() {

18         work = new thread(workThread, this);

19     };

20     

21     void parkIn() {

22         int i;

23         

24         for (i = 0; i < (int)slots.size(); ++i) {

25             if (!slots[i]) {

26                 cout << "Car is parked at slot " << i << "." << endl;

27                 slots[i] = true;

28                 fees[i] = 1;

29                 return;

30             }

31         }

32         

33         cout << "Sorry, no more slot is available." << endl;

34     };

35     

36     void getOut(int id) {

37         if (id < 0 || id > (int)slots.size() - 1) {

38             cout << "Invalid slot number." << endl;

39             return;

40         } else if (slots[id] == false) {

41             cout << "The slot is empty." << endl;

42             return;

43         }

44         

45         cout << "Car in slot " << id << " is delivered. Total fee is " << fees[id] << " bucks." << endl;

46         slots[id] = false;

47         fees[id] = 0;

48     };

49     

50     friend void workThread(ParkingLot *);

51     

52     ~ParkingLot() {

53         slots.clear();

54         fees.clear();

55         work->detach();

56         delete work;

57     };

58 private:

59     thread *work;

60     int capacity;

61     vector<bool> slots;

62     vector<int> fees;

63 };

64 

65 void workThread(ParkingLot *p)

66 {

67     while (true) {

68         // sleep for one second.

69         _sleep(1000);

70         for (int i = 0; i < p->capacity; ++i) {

71             if (p->slots[i]) {

72                 ++p->fees[i];

73             }

74         }

75     }

76 }

77 

78 int main()

79 {

80     ParkingLot *p;

81     string cmd;

82     int id;

83     

84     p = new ParkingLot(5);

85     p->start();

86     while (cin >> cmd) {

87         if (cmd == "park") {

88             p->parkIn();

89         } else if (cmd == "get") {

90             cin >> id;

91             p->getOut(id);

92         } else if (cmd == "end") {

93             break;

94         }

95     }

96     delete p;

97     

98     return 0;

99 }

 

你可能感兴趣的:(interview)