0

i am getting error on v.begin()+3 or v.end()-1 etc. why we can't operate on iterators ?

there are two list l and m

l.assign(m.begin()+3,m.end()-1) ;

this piece of code has error

[Error] no match for 'operator-' (operand types are 'std::list::iterator {aka std::_List_iterator}' and 'int')

Rakesh Joshi
  • 371
  • 1
  • 10
  • 1
    Not all (kind of) iterators can be incremented that way. – Paolo M Sep 07 '15 at 10:54
  • You might want to check out [this handy iterator reference](http://en.cppreference.com/w/cpp/iterator) and read about the different iterator types. And note that the iterator for [`std::list`](http://en.cppreference.com/w/cpp/container/list) is a [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator) which doesn't allow the operations you want, at least not directly anyway. – Some programmer dude Sep 07 '15 at 11:01

1 Answers1

0

Iterators are made to be as abstract as possible; an iterator could be a pointer into an array, a location in a stream which reads from stdin when you increment it, anything. As such, the standard arithmetic operators are only implemented for random-access iterators so that they don't hide potentially expensive operations behind simple syntax.

In order to increment/decrement any iterator by an arbitrary amount, you can use std::advance:

std::advance(it, 3); //increment by three
std::advance(it, -1); //decrement once

C++11 provides std::next and std::prev which carry this out in a more functional manner:

auto new_it = std::next(it,3); //increment by three
auto new_it = std::prev(it); //decrement once
TartanLlama
  • 63,752
  • 13
  • 157
  • 193