开发者

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

开发者 https://www.devze.com 2023-01-22 12:51 出处:网络
Lets say I have a function str_rev(string &s, int len) {} which reverses the string s of length len

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?


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


Maybe you just want to do this:

std::string::iterator it = long_str.begin() + 5;
std::reverse(it, it+10);


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));


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消