【发布时间】:2019-05-23 12:36:40
【问题描述】:
我正在编写一个代码,我正在计算持续时间,然后将其保存在列表中。
auto start_time = std::chrono::high_resolution_clock::now();
/*
*some code here
*/
auto finish_time = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time_duration = finish_time - start_time ;
现在我需要将time_duration 保存在给定索引的列表中。如果该给定索引已经包含一个值,我需要将time_duration 与该索引的当前值相加并保存。为此,我有以下列表和代码:
list <std::chrono::duration<double>> dTimeList;
auto iter = dTimeList.begin();
advance(iter, 0);
*iter+= time_duration; //Error at this line
但是运行上面的代码我得到以下错误:
这个错误很可能是因为我有一个空列表,其中没有任何项目。这就是为什么我想在第 0 个索引处添加一个项目,如下所示:
auto itr = dTimeList.begin();
advance(itr, 0);
std::chrono::duration<double> t = 0.0;
dTimeList.insert(itr, t);
但上面也给出了下面的错误。我该如何解决这个问题。谢谢
No suitable constructor available to convert double to std::chrono::duration<double>
【问题讨论】:
-
当迭代器位于
end()时,尝试推进迭代器时遇到的错误,正如您所知道的,很清楚。但是,您永远不会告诉我们第二次尝试出了什么问题。创建minimal reproducible example。 -
使用
list.push_back(t)将项目添加到列表中,不要使用advance(itr, 0) -
@TedLyngmo 我已经编辑了问题。
-
没有合适的构造函数可用于将
double转换为std::chrono<double>。但是您可以使用显式构造:std::chrono::duration<double> t{0.0};. -
@SAndrew A
list如果您想要索引,则不适合。 (它们实际上不适用于大多数事情,并且在野外很少观察到。)使用std::vector或std::deque。