Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substract 1 from bidirectional iterator

Tags:

c++

stl

I have iterator I dont want to change, but I would like to assign another iterator to the value of that iterator -1, so
it2 = --it1; is out of the question.
Problem:
it2 = it1-1; doesnt work.

error: no match for 'operator-' in 'bigger - 1' c++/4.1.1/bits/stl_bvector.h:182: note: candidates are: ptrdiff_t std::operator-(const std::_Bit_iterator_base&, const std::_Bit_iterator_base&)

ofc I could do

it2 = --it1;
it1++;

but that is horrible.

like image 619
NoSenseEtAl Avatar asked Dec 19 '25 19:12

NoSenseEtAl


1 Answers

In C++11, use std::prev from the header <iterator>:

it2 = std::prev(it1);

Prior to that, you're stuck making a copy and advancing the copy by -1 yourself:

it2 = it1;
std::advance(it2, -1);

or:

it2 = it1;
it2--;
like image 148
Lightness Races in Orbit Avatar answered Dec 22 '25 09:12

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!