运算符支持哪些格式>>用于 boost::chrono::d uration?

Which formats are supported by operator>> for boost::chrono::duration?

本文关键字:gt chrono uration 支持 boost 运算符 用于 格式      更新时间:2023-10-16

有人能告诉我从流中读取boost::chrono::duration时支持哪些格式吗?我找不到任何有关这方面的文件。我读了标题,从那里得到了一些信息,但我并不完全理解

一个非常小的测试程序:

#define BOOST_CHRONO_VERSION 2
#include <boost/chrono.hpp>
#include <boost/chrono/chrono_io.hpp>
#include <iostream>
#include <chrono>
using namespace boost::chrono;
int main() {
  boost::chrono::seconds tp1;
  std::cin >> tp1;
  std::cout << symbol_format << tp1 << std::endl;
}

当我在适当的标题中找到一些单元时,它工作得很好:

$ echo "4 seconds" | ./a.out 
4 s
$ echo "6 minutes" | ./a.out 
360 s
$ echo "2 h" | ./a.out 
7200 s

我想做的是一些组合的方法——这是行不通的:

1 minute 30 seconds
1:30 minutes
1.5 minutes
2 h 6 min 24 seconds

对我来说,解析似乎直接在第一个单元之后停止。我尝试了一些不同的分隔符(如":"、"、"、…),但没有成功。

两个问题:

  1. boost::chrono::duration中这种组合/扩展的传递可能吗?如果是,如何
  2. 如果我正确理解boost标头,分钟可以用"min"或"minute"表示,秒可以用"s"或"second"表示,但不能用"sec"表示。有人能给我指一些支持缩写的文档吗?(看起来这不是那么直接。)

有关工期单位的列表,请查看文档duration_units.hpp或查看代码

"s" / "second" / "seconds" 
"min" / "minute" / "minutes"
"h" / "hour" / > "hours"

如果你需要解析几个持续时间条目,你可以编写一个类似parse_time:的函数

#define BOOST_CHRONO_HEADER_ONLY
#define BOOST_CHRONO_VERSION 2
#include <iostream>
#include <boost/chrono.hpp>
#include <boost/algorithm/string.hpp>
#include <sstream>
#include <algorithm>
#include <stdexcept>
using namespace std;
using namespace boost;
using namespace boost::chrono;
seconds parse_time(const string& str) {
  auto first = make_split_iterator(str, token_finder(algorithm::is_any_of(",")));
  auto last = algorithm::split_iterator<string::const_iterator>{};
  return accumulate(first, last, seconds{0}, [](const seconds& acc, const iterator_range<string::const_iterator>& r) {
    stringstream ss(string(r.begin(), r.end()));
    seconds d;
    ss >> d;
    if(!ss) {
      throw std::runtime_error("invalid duration");
    }
    return acc + d;
  });
}
int main() {
  string str1 = "5 minutes, 15 seconds";
  cout << parse_time(str1) << endl; // 315 seconds
  string str2 = "1 h, 5 min, 30 s";
  cout << parse_time(str2) << endl; // 3930 seconds
  try {
    string str3 = "5 m";
    cout << parse_time(str3) << endl; // throws
  } catch(const runtime_error& ex) {
    cout << ex.what() << endl;
  }
  return 0;
}

CCD_ 4在分隔符CCD_。如果出现错误,它将抛出runtime_error

在线运行