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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
#include <iostream> #include <vector> #include <string> #include <thread> #include <chrono> // Task class to represent a task with a name and duration class Task { public: Task(const std::string& name, int duration) : name(name), duration(duration), timeLeft(duration) {} // Update the task by one time unit void update() { if (timeLeft > 0) { --timeLeft; } } // Check if the task is complete bool isComplete() const { return timeLeft <= 0; } // Print the task status void printStatus() const { std::cout << "Task: " << name << " | Time Left: " << timeLeft << "s" << (isComplete() ? " (Complete)" : "") << std::endl; } private: std::string name; int duration; int timeLeft; }; // Function to simulate time management with tasks void simulateTimeManagement(std::vector<Task>& tasks) { while (true) { bool allComplete = true; for (auto& task : tasks) { task.update(); task.printStatus(); if (!task.isComplete()) { allComplete = false; } } if (allComplete) { std::cout << "All tasks are complete!" << std::endl; break; } std::this_thread::sleep_for(std::chrono::seconds(1)); // Simulate time passing std::cout << std::endl; } } int main() { // Create tasks with name and duration std::vector<Task> tasks = { Task("Task 1", 5), Task("Task 2", 3), Task("Task 3", 7) }; std::cout << "Time Management Simulation\n"; simulateTimeManagement(tasks); return 0; } |
Explanation
- Task Class:
- Attributes:
name
: Name of the task.duration
: Total duration of the task in seconds.timeLeft
: Remaining time for the task.
Advertisement - Methods:
update()
: Reduces thetimeLeft
by one unit if the task is not complete.isComplete()
: Checks if the task is complete.printStatus()
: Prints the current status of the task, including time left and whether it is complete.
Advertisement
- Attributes:
- simulateTimeManagement Function:
- Continuously updates and prints the status of each task.
- Checking Completion: If all tasks are complete, the simulation ends.
- Time Simulation: Uses
std::this_thread::sleep_for
to simulate the passage of time (1 second per iteration).
- Main Function:
- Creates a list of tasks with different names and durations.
- Starts the time management simulation by calling
simulateTimeManagement
.
Usage
- Tasks: The program handles multiple tasks with specified durations, updating their status over time.
- Time Management: Simulates the progress of tasks, printing their status every second until all tasks are complete.