next iterator position without mutation

C

Cagdas Ozgenc

Greetings.

Is there a convinient way to get the next iterator position without mutating
the iterator for non-random access containers? For example,

i + 1

instead of

i++

Thanks
 
A

Attila Feher

Cagdas said:
Greetings.

Is there a convinient way to get the next iterator position without
mutating the iterator for non-random access containers? For example,

i + 1

instead of

i++

Nope. For input or output iterators you cannot even read the same place
twice. I might be wrong, but for forward or bidirectional iterators you may
copy the iterator and increment the copy to "take a peek".
 
C

Cagdas Ozgenc

Nope. For input or output iterators you cannot even read the same place
twice. I might be wrong, but for forward or bidirectional iterators you may
copy the iterator and increment the copy to "take a peek".
That's bad news. The following code would be quite dangerous then:

template<typename Iterator>
Iterator operator+(Iterator const& input,size_t offset) {
Iterator output = input;
while(offset > 0) {
++output;
offset--;
}
return output;
}

I can't find a forward_iterator class to make the above function iterator
type-safe. What's wrong with these STL iterators?

Thanks
 
A

Attila Feher

Cagdas said:
That's bad news. The following code would be quite dangerous then:

template<typename Iterator>
Iterator operator+(Iterator const& input,size_t offset) {
Iterator output = input;
while(offset > 0) {
++output;
offset--;
}
return output;
}

I can't find a forward_iterator class to make the above function
iterator type-safe. What's wrong with these STL iterators?

You have iterator traits, OMHO you can make a compile time assertion if the
function template is being instantiated with the wrong iterator category.
 
C

Cagdas Ozgenc

You have iterator traits, OMHO you can make a compile time assertion if
the
function template is being instantiated with the wrong iterator category.

Can you give a small example, or give pointers on that matter.

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top