简体   繁体   English

推进std :: copy中的列表迭代器时出错

[英]Error advancing a list iterator in std::copy

#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
using std::list;
using std::endl;
using std::cout;
using std::iterator;
int main()
{
    list<int> list_int{ 0,1,2,3,4,5,6,7,8,9 };
    list<int> list_int2;

    copy(list_int.crbegin()+3 , list_int.crbegin()+8,back_inserter(list_int2));
    for (auto &ele : list_int2)
        cout << ele << endl;

    return 0;
}

what is the wrong?I am so confused.I think the wrong is about the copy function. 怎么了?我很困惑,我认为错是关于复制功能。

error: 错误:

在此处输入图片说明

You cannot advance a list iterator (bidirectional non-random) by incrementing it with more than one. 您不能通过将列表迭代器增加一个以上来推进列表迭代器 (双向非随机)。 In other words, only operator++ and operator-- are defined for bi-directional iterators. 换句话说,仅为双向迭代器定义了operator++operator-- Use std::next instead, 使用std::next代替,

copy(std::next(list_int.crbegin(), 3), 
     std::next(list_int.crbegin(), 8),
     back_inserter(list_int2));

std::next will tag-dispatch to the correct internal iterator function which in effect will increment the iterator one by one repeatedly. std::next标记分派到正确的内部迭代器函数,该函数实际上将迭代器一一递增。

list_int and list_int2 are of type std::list . list_intlist_int2的类型为std::list Iterators of std::list do not support random access. std::list迭代器不支持随机访问。 Therefore you cannot advance them by adding an integer like list_int.crbegin() + 3 . 因此,您不能通过添加诸如list_int.crbegin() + 3的整数来推进它们。

You can make a copy of the list iterators and use std::advance to advance them. 您可以复制列表迭代器,并使用std::advance推进它们。 See docs 查看文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM