1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
#include <iostream> #include <vector> #include <queue> #include <algorithm> class Elevator { public: Elevator(int numFloors) : currentFloor(0), numFloors(numFloors) {} void request(int floor) { if (floor < 0 || floor >= numFloors) { std::cerr << "Invalid floor request.\n"; return; } if (floor != currentFloor) { requests.push(floor); } } void operate() { while (!requests.empty()) { int targetFloor = requests.front(); requests.pop(); moveToFloor(targetFloor); } } private: int currentFloor; int numFloors; std::queue<int> requests; void moveToFloor(int targetFloor) { std::cout << "Moving from floor " << currentFloor << " to floor " << targetFloor << "\n"; currentFloor = targetFloor; } }; int main() { int numFloors = 5; // Number of floors in the building Elevator elevator(numFloors); int numRequests; std::cout << "Enter the number of floor requests: "; std::cin >> numRequests; for (int i = 0; i < numRequests; ++i) { int floor; std::cout << "Enter floor request " << i + 1 << ": "; std::cin >> floor; elevator.request(floor); } std::cout << "Starting elevator operation...\n"; elevator.operate(); return 0; } |
Explanation
- Class
Elevator
:- Purpose: Simulates an elevator system handling floor requests.
- Attributes:
currentFloor
: The current floor of the elevator.numFloors
: Total number of floors in the building.requests
: Queue of requested floors.
- Methods:
request(int floor)
: Adds a floor request to the queue if the floor is valid and different from the current floor.operate()
: Processes each request by moving the elevator to the requested floor.moveToFloor(int targetFloor)
: Moves the elevator to the specified floor and updates the current floor.
- Main Function:
- Setup: Initializes an elevator with a given number of floors.
- Request Input: Prompts the user to enter the number of floor requests and the specific floors.
- Operation: Calls the
operate()
method to handle and process all requests.
Usage
- Elevator Simulation: Demonstrates a basic elevator system that processes requests and moves between floors.
- User Interaction: Allows users to input floor requests and see the elevator’s response.