Accept either an iterator or a reverse_iterator

  • Thread starter Boogie El Aceitoso
  • Start date
B

Boogie El Aceitoso

Hi,


I'm writng a function that works an a std::string and should accept either an
iterator or a reverse_iterator. How can I do this? O:)
 
L

lallous

Boogie El Aceitoso said:
Hi,


I'm writng a function that works an a std::string and should accept either an
iterator or a reverse_iterator. How can I do this? O:)

Function parameter overloading?

Regards,
Elias
 
M

Martijn Lievaart

Hi,


I'm writng a function that works an a std::string and should accept either an
iterator or a reverse_iterator. How can I do this? O:)

The way this is done most often, is to use a template:

template<typename T1, typename T2>
void print(T1 start, T2 end)
{
while (start != end)
cout << *start++;
}

HTH,
M4
 
J

Josh Sebastian

The way this is done most often, is to use a template:

template<typename T1, typename T2>
void print(T1 start, T2 end)

Shouldn't the iterators be the same type?

{
while (start != end)
cout << *start++;
}

HTH,
M4

Josh
 
M

Martijn Lievaart

Shouldn't the iterators be the same type?

No, this precludes the use of a const_iterator for one and a normal
iterator for the other. For most cases it will work though.

M4
 
J

Josh Sebastian

No, this precludes the use of a const_iterator for one and a normal
iterator for the other.

Maybe I'm just lacking in imagination, but that doesn't seem terribly
useful to me. In theory, the two iterators should point to elements of the
same sequence. I don't really see why you'd have a const- and
non-const-iterator to the same sequence.
For most cases it will work though.

I'd hope so, as that's how the standard library functions do it. :-}

Josh
 
M

Martijn Lievaart

Maybe I'm just lacking in imagination, but that doesn't seem terribly
useful to me. In theory, the two iterators should point to elements of the
same sequence. I don't really see why you'd have a const- and
non-const-iterator to the same sequence.


I'd hope so, as that's how the standard library functions do it. :-}

Hmm, I did it that way, because I remembered that the STL does it my way.
I was wrong. It is only relevant when the iterators really differ, like
input/output iterators.

Thanks for the correction.

M4
 

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
474,148
Messages
2,570,838
Members
47,385
Latest member
Joneswilliam01

Latest Threads

Top