boost::progress_display 是 Boost 庫中一個輕量級的控制台進度條組件,適合在命令行程序中顯示長時間任務的進度。頭文件:<boost/progress.hpp>。
#include
#include
#include // usleep
using namespace boost;
using namespace std;
int main() {
progress_display pd(200); // 總步數 200
for (int i = 0; i < 100; ++i) {
++pd; // 遞增進度
usleep(10000); // 模擬耗時操作
}
cout << "\n第一階段完成\n";
pd.restart(200); // 重置總步數
pd += 100; // 直接增加 100 步
for (int i = 0; i < 100; ++i) {
++pd;
usleep(10000);
}
cout << "\n完成\n";
return 0;
}
0% 10 20 30 40 50 60 70 80 90 100% |----|----|----|----|----|----|----|----|----|----| ************************** 第二階段 0% 10 20 30 40 50 60 70 80 90 100% |----|----|----|----|----|----|----|----|----|----| ***************************************************
| 函數 | 說明 |
|---|---|
progress_display(expected_count) | 構造函數,預期總步數 |
operator++() | 進度 +1,自動更新顯示 |
operator+=(unsigned int) | 進度增加指定值 |
restart(expected_count) | 重置進度條,新的總步數 |
count() | 獲取當前已完成步數 |
expected_count() | 獲取預期總步數 |
boost::progress_display 以極簡 API 提供開箱即用的控制台進度條,無需手動處理光標控制、刷新邏輯。對於 C++ 控制台程序,是快速添加進度反饋的最佳選擇之一。