【问题标题】:Convert chrono::duration to string or C string将 chrono::duration 转换为字符串或 C 字符串
【发布时间】:2017-03-17 20:24:58
【问题描述】:

我正在尝试创建一个表格(一个 9 x 11 的数组)来存储一个函数通过几个排序函数所花费的时间。

我想我希望表格是一个字符串。我目前无法解决如何将chrono 转换为string 并且无法在网上找到任何资源。

我是否需要放弃为表格输入字符串,或者有没有办法将这些时间差存储在字符串中?

for (int i = 0; i<8;i++) // sort 8 different arrays
{ 
    start = chrono::system_clock::now(); 
    //Sort Array Here
    end = chrono::system_clock::now();
    chrono::duration<double> elapsed_seconds = end-start;
    table[1][i] = string(elapsed_seconds)   // error: no matching conversion for functional style cast
}

【问题讨论】:

  • 你不想elapsed_seconds.count()吗?顺便说一句; std::string 没有一个构造函数来进行你想要的转换。

标签: c++ string type-conversion chrono


【解决方案1】:

您需要流式传输到std::ostringstream,然后从该流中检索字符串。

要流式传输chrono::duration,您可以使用其.count() 成员函数,然后您可能想要添加单位(例如ns 或任何单位)。

这个免费的、仅包含标头的开源库:https://howardhinnant.github.io/date/chrono_io.html 通过自动为您附加单位,让duration 的流式传输变得更加容易。

例如:

#include "chrono_io.h"
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std;
    using namespace date;
    ostringstream out;
    auto t0 = chrono::system_clock::now();
    auto t1 = chrono::system_clock::now();
    out << t1 - t0;
    string s = out.str();
    cout << s << '\n';
}

只为我输出:

0µs

没有"chrono_io.h" 看起来更像:

    out << chrono::duration<double>(t1 - t0).count() << 's';

还有可以使用的to_string 系列:

    string s = to_string(chrono::duration<double>(t1 - t0).count()) + 's';

但是,没有直接来自chrono::durationto_string。您必须使用.count()“逃脱”,然后添加单位(如果需要)。


更新

C++20 将"chrono_io.h" 的功能直接引入&lt;chrono&gt;。所以不再需要免费的开源库。

【讨论】:

    【解决方案2】:

    你可以像这样使用chrono::duration_cast

    #include <iostream>
    #include<chrono>
    #include <sstream>
    
    using namespace std;
    
    int main()
    {
        chrono::time_point<std::chrono::system_clock> start, end;
        start = chrono::system_clock::now();
        //Sort Array Here
        end = chrono::system_clock::now();
        chrono::duration<double> elapsed_seconds = end - start;
        auto x = chrono::duration_cast<chrono::seconds>(elapsed_seconds);
    
        //to_string
        string result = to_string(x.count());
    
        cout <<  result;
    }
    

    结果:

    - 以秒为单位:

    0 秒

    - 以 µs 为单位:

    auto x = chrono::duration_cast<chrono::microseconds>(elapsed_seconds);
    

    结果:

    535971µs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 2015-02-18
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      相关资源
      最近更新 更多