【问题标题】:How to insert item in list at given index in c++如何在C++中给定索引的列表中插入项目
【发布时间】:2019-10-09 19:25:45
【问题描述】:

我正在处理c++ 代码,我需要在列表的给定索引处插入一个项目。我有两个清单:

list <int> objectIdList;  //This list will save id's of object
list <double> objectIdDtimeList;  //This list will save time duration of each particular object id.

我有一个代码,我将所有对象 ID 保存在 objectIdList 中,如下所示:

Index    Value
[0]      3
[1]      6
[2]      2

现在我需要将这些对象 ID (3, 6, 2) 的持续时间保存在 objectIdDtimeList 中。我的计划是将持续时间保存在索引处的列表中,即对象ID。例如,对于对象 id 3,其总持续时间将保存在索引 3 的列表中。对于 id 6 的对象,其持续时间将保存在索引 6 处。

为此,我计划使用list.insert(),如下所示:

time_t start, end;
time(&start);

/*
 * SOME CODE HERE
 * SOME CODE HERE
*/

for (auto id : objectIdList)
{
    time(&end);
    double time_passed = difftime(current, start);  //Getting the time duration in seconds

    list<int>::iterator it = objectIdList.begin();

    advance(it, id);  // iterator to point to object id index

    objectIdDtimeList.insert(it, time_passed);
}

但上面的代码给出了以下错误:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0304   no instance of overloaded function "std::list<_Ty, _Alloc>::insert [with _Ty=double, _Alloc=std::allocator<double>]" matches the argument list

Severity    Code    Description Project File    Line    Suppression State
Error   C2664   'std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>> std::list<_Ty,std::allocator<_Ty>>::insert(std::_List_const_iterator<std::_List_val<std::_List_simple_types<_Ty>>>,unsigned __int64,const _Ty &)': cannot convert argument 1 from 'std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>' to 'std::_List_const_iterator<std::_List_val<std::_List_simple_types<_Ty>>>'   

有什么方法可以实现这个功能。有没有其他选择可以做到这一点。谢谢

【问题讨论】:

    标签: c++ visual-studio list insert


    【解决方案1】:

    您在这里混合了两种不同的迭代器类型。

    list<int>::iterator it = objectIdList.begin();
    

    这是一个指向objectIdList 的迭代器,但为了调用objectIdDtimeList.insert(...),您需要一个指向objectIdDtimeList 的迭代器。因此,尝试将上面的行更改为

    auto it = objectIdDtimeList.begin();
    

    使用id 推进正确的迭代器应该仍然有效,并且插入应该成功。

    【讨论】:

      猜你喜欢
      • 2016-03-20
      • 1970-01-01
      • 2021-10-14
      • 2023-03-21
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      相关资源
      最近更新 更多