用C++实现定时时钟,可设置多个时钟
时间: 2024-05-06 10:16:18 浏览: 9
你可以使用C++中的计时器(timer)来实现定时时钟,同时使用容器(比如vector)来存储多个时钟的信息。以下是一个简单的示例代码:
```c++
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
using namespace std;
struct Clock {
int hour;
int minute;
int second;
bool operator<(const Clock& other) const {
return hour < other.hour ||
(hour == other.hour && minute < other.minute) ||
(hour == other.hour && minute == other.minute && second < other.second);
}
};
int main() {
vector<Clock> clocks = {{10, 0, 0}, {12, 30, 0}, {18, 45, 0}}; // 初始化三个时钟
auto start_time = chrono::system_clock::now(); // 获取程序开始时间
while (true) {
auto current_time = chrono::system_clock::now(); // 获取当前时间
auto elapsed_seconds = chrono::duration_cast<chrono::seconds>(current_time - start_time).count(); // 计算程序已经运行的秒数
// 判断每个时钟是否到达设定时间
for (auto& clock : clocks) {
int total_seconds = clock.hour * 3600 + clock.minute * 60 + clock.second;
if (total_seconds == elapsed_seconds) {
cout << "Time's up! " << clock.hour << ":" << clock.minute << ":" << clock.second << endl;
}
}
this_thread::sleep_for(chrono::milliseconds(100)); // 程序暂停100毫秒,减少CPU占用率
}
return 0;
}
```
在上述代码中,我们使用了`chrono`库来获取当前时间和计算时间差,使用了`thread`库来暂停程序。我们也定义了一个`Clock`结构体来存储每个时钟的信息,并且重载了小于号`<`来方便比较时钟的先后。程序会不断循环,每100毫秒检查一次每个时钟是否到达设定时间,如果是则输出提示信息。