簡體   English   中英

如何在C ++中的列表中保存計時時間

[英]How to save chrono time in list in C++

我正在嘗試在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,std :: allocator <_Ty >> :: insert(std :: _ List_const_iterator >>,unsigned __int64,const _Ty&)':無法將參數2從' std :: chrono :: steady_clock :: time_point'到'_Ty &&'

std::chrono::high_resolution_clock::now()返回一個實例

std::chrono::high_resolution_clock::time_point

...由於充分的原因,不能轉換為double 如果要存儲時間點,則需要有足夠的列表:

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

在這里使用list<double>是錯誤的。 您需要存儲類型為list<decltype(start)> ,該list<std::chrono::time_point<std::chrono::high_resolution_clock>>list<std::chrono::time_point<std::chrono::high_resolution_clock>> 下面的代碼應該工作:

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

正如評論中指出的那樣:“您需要在列表中存儲正確的類型,即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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM