Can we increase the iterator without the 'advance' function? C++11

  • A+
Category:Languages

I know we can use advance() function to increment the iterator. We also use iterator++ to increase the iterator by one position. Why we cannot use it+=2?

int main() {     list<int> l1{1, 2, 3, 5, 6};     list<int> l2{2, 6, 8};     auto it = l1.begin();     advance(it, 2);         //works     it++;                   //works     // it+=2;                  //not work     l2.splice(l2.begin(), l1, it);      for(int a: l2) cout<<a<<" ";     cout<<endl;      return 0; } 

You can run the above code here

 


operator += is only supported by RandomAccessIterator; note that it's supposed to have constant complexity.

The iterator of std::list is BidirectionalIterator, which doesn't support operator +=. (The iterator of std::vector and std::array is RandomAccessIterator.)

Note that both of them could be used with std::advance, when used for RandomAccessIterator complexity is constant; when used for other InputIterators (including BidirectionalIterator) complexity is linear. That means using std::advance is a good idea because it's more general and could take advantage of the benefit of RandomAccessIterator automatically.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: