NoSenseEtAl
NoSenseEtAl

Reputation: 30118

How to substract 1 from bidirectional iterator

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.

Upvotes: 2

Views: 111

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

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--;

Upvotes: 8

Jason C
Jason C

Reputation: 40376

You can do it like this:

it2 = it1; 
-- it2;

it1 will not be modified.

Upvotes: 1

Related Questions