【问题标题】:STL List adding and removing chosen elementSTL 列表添加和删除所选元素
【发布时间】:2013-06-14 00:13:14
【问题描述】:

我正在编写使用列表的简单程序。我已经创建了包含所有功能的列表,但现在我想将其转换为 STL。我已经成功完成了我的一些功能,但我坚持使用一个应该添加新元素并删除用户选择的元素的功能。

这是我的代码:

list <Komputer> lista_komputerow_STL;
list <Komputer>::iterator it;
///This should add an element:
lista_komputerow_STL.push_back(Komputer(nazwa));
///This should remove chosen element:
int element;

for(int i=0;i<(element-1);i++)
{it++;}
lista_komputerow_STL.erase(it);

我对 STL 完全陌生,现在对我来说似乎很多,但我希望在你的帮助下我会得到它。

【问题讨论】:

    标签: c++ list stl


    【解决方案1】:

    你必须初始化迭代器:

    list <Komputer>::iterator it = lista_komputerow_STL.begin();
    

    还没有初始化所选的element,我想你的 for 语句应该是:

    int element = 0;
    for(int i=0; i<element; i++)      // Without the '-1'
    ...
    

    我建议使用 std::advance 来移动迭代器而不是 for 循环:

    std::advance(it, element);
    

    但是你可以看看base example,如果有什么你不明白的,请告诉我......

    【讨论】:

      猜你喜欢
      • 2015-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 2018-07-02
      • 2020-04-10
      相关资源
      最近更新 更多