Efficient way to get a reversed copy of std::string

Viewed 249

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.

3 Answers

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.

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.

Like others have said you should first decide what is more meaningful to your code-base, style or speed. If style, just use std::reverse which has an average runtime of O(n). If speed is a bottleneck and you run this reverse string method all the time, I would consider creating a doubly-linked list. Then reversing the LL can happen in O(1) runtime.

Related