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::listis BidirectionalIterator, which doesn't supportoperator +=. (The iterator ofstd::vectorandstd::arrayis 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::advanceis a good idea because it's more general and could take advantage of the benefit of RandomAccessIterator automatically.