By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,107 Members | 1,281 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,107 IT Pros & Developers. It's quick & easy.

efficient approach to reverse a std::string object

P: n/a
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?

Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"July" <ju**********@yahoo.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
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.
Jul 23 '05 #2

P: n/a


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.

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.