efficient approach to reverse a std::string object

J

July

Hello all

Recentlly, I was asked to write a program in which there is a function
that need to reverse a std::string object.
I wrote like this:
string ReverseString(const string& srcStr)
{
string str;
for(size_t i = 0; i < srcStr.length(); ++i)
str += srcStr[srcStr.length() - i - 1];

return str;
}

Is there any potential error in the ReverseString function?
And if there is any more efficient approach to do this?
 
B

benben

July said:
Hello all

Recentlly, I was asked to write a program in which there is a function
that need to reverse a std::string object.
I wrote like this:
string ReverseString(const string& srcStr)
{
string str;
for(size_t i = 0; i < srcStr.length(); ++i)
str += srcStr[srcStr.length() - i - 1];

return str;
}

Is there any potential error in the ReverseString function?

That you can debug...
And if there is any more efficient approach to do this?

std::reverse does exactly that.
 
M

msalters

July schreef:
Hello all

Recentlly, I was asked to write a program in which there is a function
that need to reverse a std::string object.
I wrote like this:
string ReverseString(const string& srcStr)
{
string str;
for(size_t i = 0; i < srcStr.length(); ++i)
str += srcStr[srcStr.length() - i - 1];

return str;
}

Is there any potential error in the ReverseString function?
Seems Ok.
And if there is any more efficient approach to do this?

Reverse iterators:

string ReverseString(const string& srcStr) {
return string( srcStr.rbegin(), srcStr.rend() );
}

You might not even need the function, if you see how simple it
really is.

HTH,
Michiel Salters.
 

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,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top