使用std :: copy复制std :: list并使用std :: list :: erase删除

用户名

在下面的示例代码中,在给示例列表分配了编号之后,我尝试与之复制容器,std::copy但问题是在运行时它说“无法取消引用最终列表迭代器”。

我的问题是如何复制列表,以便将重复的范围插入列表的末尾?

到最后,因为我以后需要能够删除重复的范围,这就是为什么将新范围的开头保存到迭代器的原因。

#include <iostream>
#include <list>
#include <algorithm>

void print(std::list<int>& ref)
{
    for (auto& num : ref)
    {
        std::cout << num << std::endl;
    }
}

int main()
{
    std::list<int> mylist{ 1, 2, 3, 4 };
    std::list<int>::iterator iter = mylist.end();

    std::cout << "INITIAL LIST NUMBERS" << std::endl;
    print(mylist);

    // duplicate list, will cause runtime error
    iter = std::copy(mylist.begin(), mylist.end(), --mylist.end());

    std::cout << "COPIED LIST IS NOW CONTAINS DUPLICATE NUMBERS" << std::endl;
    print(mylist);

    // remove previsous duplication
    mylist.erase(iter, mylist.end());

    std::cout << "AFTER REMOVAL OF COPIED LIST SHOULD BE SAME AS INITIAL LIST" << std::endl;
    print(mylist);

    std::cin.get();
    return 0;
}
润滑脂

您可以使用std::copy_n这可以避免的问题std::copy,当使用std::back_inserter(mylist)和始终有效的mylist.end()迭代器进行填充时,该循环将执行插入的无限循环

const std::size_t n = mylist.size();
std::copy_n(mylist.cbegin(), n, std::back_inserter(mylist));

然后,重复数据删除可与

mylist.erase(std::next(mylist.begin(), n), mylist.end());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++-std :: list.erase()不删除元素

std :: list转换和复制

在类中使用std :: vector或std :: list的Visual C ++ 2012

使用迭代器对std :: list进行排序

如何在std :: list中使用递归?

连续使用 std::list 导致崩溃

使用std :: copy复制到std :: deque

使用容器中元素的别名使用std :: list :: remove删除元素是否正确?

std :: list iterator.erase()导致无效的指针

离开成功使用 std::erase 的方法后,错误的元素被删除

使用std :: string :: erase从字符串中删除起始字符

在非空std :: list <int>上使用std :: list.back()时出现“分段错误”

为什么std :: forward_list ::: remove和std :: erase <std :: forward_list>具有不同的值类型?

通过引用从std :: list中删除元素

std :: list remove_if是否删除节点?

使用 std::erase 调试断言失败

使用std :: vector和std :: list时Linux内存使用率排在最前面

使用std :: initializer_list构造函数而不会产生歧义?

使用std :: initializer_list作为成员变量

使用boost ptree将std :: list序列化为json

我应该使用 std::list 还是有更好的方法?

如何使用 std::list 作为暴露节点的列表的接口的实现?

使用不带标签的Core.Std.List.fold_left

在MyClass'函数中使用std :: list :: remove_if

使用删除的功能-std :: atomic

使用初始化器列表作为值时,无法插入std :: list <std :: vector <int >>?

使用作为参数传递的std :: intializer_list初始化std :: array

std :: list是循环的吗?

std :: list c的数组