Home > Mobile >  Efficient way to get a reversed copy of std::string
Efficient way to get a reversed copy of std::string

Time:10-14

Dealing with algorithmic tasks I frequently need to get a copy of reversed std::string. Also, the source string should not be modified. As far as I concerned, there are two ways to do it:

  1. Use std::reverse :
// std::string sourceString has been initialized before.
std::string reversedString = sourceString;
std::reverse(reversedString.begin(), reversedString.end());
  1. Use reverse iterators. This one I found on the Internet:
// std::string sourceString has been initialized before.
std::string reversedString{sourceString.rbegin(), sourceString.rend()};

My question is which approach I should prefer according to efficiency and best practices. C-style solutions are not in my concern, I am only interested in STL-way approaches.

CodePudding user response:

My question is which approach I should prefer according to efficiency

The one which should be preferred according to efficiency is the one that has been measured to be more efficient. Both have the same asymptotic complexity.

But, I won't bother to measure the difference unless it happens to be a bottleneck. I prefer 2, but it's subjective.

CodePudding user response:

I could say that constructing a data structure with the right data initially is faster generally, but general statements about performance is generally wrong. You should measure the performance and benchmark if you're concerned about performance.

If you're not concerned enough about performance to write benchmark code, then you should take the style that looks the best for you.


Also, you forgot C 20 style:

auto reversed = sourceString | std::views::reverse;
std::string reversedString{begin(reversed), end(reversed)};

Which in the end is not that different from the iterator range style since the string still need a iterator pair.

  • Related