views:

78

answers:

4

Lets say I have a function

str_rev(string &s, int len) {}

which reverses the string s of length len

I want to reverse a substring of long string starting at index 5 and of length 10

for this I was forced to first call substring function and then call the str_rev function passing the substring

sub_string = long_str.substr(5, 10)
str_rev(sub_string, 10);

Is there any way to achieve this without actually creating a temporary object?

+8  A: 

Make your function take iterators (or, rather, use std::reverse()) and pass in iterators delimiting the substring.

sbi
thankyou sbi ..
ajayreddy
+1  A: 

If you use char* instead of std::string, you can pass a pointer to any two chars in the string. However, using char* is generally not a good idea.

baruch
What you mean is iterators, then, like sbi suggests.
GMan
No, I meant pointer. I didn't know you can have an iterator for the individual chars of a std::string. Thanks for the new insight.
baruch
@baruch: It makes no sense to say "I didn't mean iterator, I meant pointer". A pointer _is_ a random-access iterator.
sbi
I know that. What I meant was that I didn't know you could use a random access iterator over the chars of a std::string. I thought that in order to use pointers to individual chars, you had to use a char*, and therefore pointers (even though they can be used in place of iterators, in this case they are still technically pointers)
baruch
+1  A: 

rather than int len, pass a parameter which defines a range:

str_rev(string &s, const t_unsigned_range& range) {/* ... */}

and

str_rev(long_str, t_unsigned_range(5,10));
Justin
+2  A: 

Maybe you just want to do this:

std::string::iterator it = long_str.begin() + 5;
std::reverse(it, it+10);
PigBen
Hmm... I wonder why there's no reverse_n. Does anybody know if there's a good reason for that?
PigBen
@Eugen: I don't understand, how does the one obviate the other?
PigBen
thank you pigben and all, I will go for iterators
ajayreddy
@PigBen: Because there doesn't need to be. Just add `n` to your starting iterator.
GMan
@GMan: But that would only work on random access iterators. Regardless, I just thought of the probable reason. It's because reverse requires a valid last iterator from the start, because it's iterating from both sides. Whereas functions like copy, generate and fill can use insert iterators to create elements along the way.
PigBen
@PigBen: You can use `std::advance`. But yes, you're right; I was hoping you'd ask "why is there `fill_n`, for example?" But you figured it out. :)
GMan
@PigBen: err, I was thinking about something else... Deleted the useless comment...
Eugen Constantin Dinca