Efficient conversion of string iterators to pointers

D

Dom Bannon

I have a lot of string-handling code that uses both STL strings and
C-style pointers, for various reasons. It's not really practical to
convert all the code to use iterators instead of pointers.

My problem is that I occasionally have to convert pointers to
iterators to do something useful. To use 'replace', for example, I
have to do something like this:

const char *tkbeg, *tkend; // ptrs in 'linebuf'
....
string::iterator it1 = linebuf.begin() + (tkbeg - linebuf.c_str());
string::iterator it2 = linebuf.begin() + (tkend - linebuf.c_str());
linebuf.replace(it1, it2, getReplacement());

Is there a better way to do this? My concern is that the conversion is
so complex that the compiler is unlikely to recognise it as a no-op,
which is presumably what it is for most compilers.

Thanks -

Dom
 
V

Victor Bazarov

I have a lot of string-handling code that uses both STL strings and
C-style pointers, for various reasons.

Have you examined those reason closely? Are they truly valid? You seem
concerned about the duality of your system which indicates that you have
doubts about those reasons.
> It's not really practical to
convert all the code to use iterators instead of pointers.

If you kept indices instead, you could always convert them to either
pointers or iterators... Just a thought.
My problem is that I occasionally have to convert pointers to
iterators to do something useful. To use 'replace', for example, I
have to do something like this:

const char *tkbeg, *tkend; // ptrs in 'linebuf'
...
string::iterator it1 = linebuf.begin() + (tkbeg - linebuf.c_str());
string::iterator it2 = linebuf.begin() + (tkend - linebuf.c_str());
linebuf.replace(it1, it2, getReplacement());

Is there a better way to do this? My concern is that the conversion is
so complex that the compiler is unlikely to recognise it as a no-op,

Which conversion is a no-op? Are you saying that linebuf.begin() and
linebuf.c_str() return essentially the same thing? Well, they don't.
which is presumably what it is for most compilers.

I don't agree. Iterator and pointers to elements aren't the same thing
and aren't really meant to be the same thing. However, consider this:
if instead of keeping pointers to the string elements that you get from
using 'c_str' member, you actually used the 'data' member, then you
don't have to convert to iterators when passing to 'replace'. Pass
those pointers, they are iterators, semantically.

V
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top