【问题标题】:How to save chrono time in list in C++如何在 C++ 中的列表中保存计时时间
【发布时间】:2019-10-09 23:14:18
【问题描述】:

我正在编写 c++ 代码,我试图将 chrono time 保存在一个列表中,以便以后可以读取该值并计算持续时间。

在列表中保存时间的原因是因为我有多个对象,我需要捕获检测到该对象的当前时间,然后当该对象消失时,我必须计算该对象的持续时间.

list <double> dTimeList;

auto start = std::chrono::high_resolution_clock::now();

auto it = dTimeList.begin();
advance(it, detection.object_id);

dTimeList.insert(it, start ); //But this is giving error

错误(活动)E0304 重载函数“std::list<_ty _alloc>::insert [with _Ty=double, _Alloc=std::allocator]”的实例与参数列表不匹配

错误 C2664 'std::_List_iterator>> std::list<_ty>>::insert(std::_List_const_iterator>>,unsigned __int64,const _Ty &)': 无法转换参数2 从 'std::chrono::steady_clock::time_point' 到 '_Ty &&'

【问题讨论】:

  • dTimeList的类型是什么?
  • @Holt 抱歉,我已经更新了类型。
  • 您需要在列表中存储正确的类型,即std::chrono::high_resolution_clock::time_point,而不是doublestd::chrono::time_point 不能隐式转换为数值类型,这是有充分理由的。

标签: c++ c++11 time chrono


【解决方案1】:

在这里使用list&lt;double&gt; 是错误的。您需要存储list&lt;decltype(start)&gt; 类型的列表,与list&lt;std::chrono::time_point&lt;std::chrono::high_resolution_clock&gt;&gt; 相同。以下代码应该可以工作:

auto start = std::chrono::high_resolution_clock::now();
list <decltype(start)> dTimeList;

auto it = dTimeList.begin();
advance(it, detection.object_id);
dTimeList.insert(it, start );

请注意,我更改了顺序或列表声明和start。当然,您也可以使用一些typedef/using 声明符。

最后,为了完整起见,high_resolution_clock 对上述类型有一个自己的别名,std::chrono::high_resolution_clock::time_point

【讨论】:

    【解决方案2】:

    std::chrono::high_resolution_clock::now() 返回一个实例

    std::chrono::high_resolution_clock::time_point
    

    ...出于充分的理由,它不能转换为double。如果你想存储时间点,你需要有一个足够的列表:

    std::list<std::chrono::high_resolution_clock::time_point> dTimeList;
    

    【讨论】:

      【解决方案3】:

      正如 cmets 中所指出的:“您需要在列表中存储正确的类型,即 std::chrono::high_resolution_clock::time_point,而不是 double。std::chrono::time_point 不可隐式转换数字类型,有充分的理由。”

      我在下面提供了一个小的工作示例:

      #include <iostream>
      #include <chrono>
      #include <vector>
      #include <thread>
      
      int main()
      {
          std::vector<std::chrono::time_point<std::chrono::system_clock>> dTimeList;
      
          dTimeList.push_back(std::chrono::high_resolution_clock::now());
          std::this_thread::sleep_for (std::chrono::seconds(1));
          dTimeList.push_back(std::chrono::high_resolution_clock::now());
      
          std::chrono::duration<double> difference = dTimeList[0]-dTimeList[1];
          std::cout << "Time difference is: " << difference.count() << std::endl;
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-02-07
        • 1970-01-01
        • 2019-09-04
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 2017-04-22
        • 1970-01-01
        • 2020-05-06
        相关资源
        最近更新 更多