Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a substring without actually creating an temporary object in c++

Tags:

c++

string

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?

like image 334
ajayreddy Avatar asked Dec 09 '22 13:12

ajayreddy


2 Answers

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

like image 163
sbi Avatar answered May 29 '23 09:05

sbi


Maybe you just want to do this:

std::string::iterator it = long_str.begin() + 5;
std::reverse(it, it+10);
like image 30
Benjamin Lindley Avatar answered May 29 '23 09:05

Benjamin Lindley