C++ Algorithm Reverse: std::reverse, reverse_copy & std::rotate

C++ Algorithm Reverse: std::reverse, reverse_copy & std::rotate

이 글의 핵심

Practical guide to reverse, reverse_copy, and rotate for sequences and strings.

Introduction

Reverse algorithms flip element order or rotate segments: reverse, reverse_copy, and rotate work on vectors, arrays, and std::string.


1. std::reverse

Full range, subrange, and string examples match the Korean article (same code).


2. std::reverse_copy

Copies elements in reverse order to an output iterator (e.g. back_inserter or raw array).


3. std::rotate

std::rotate(first, middle, last) leaves elements in order middle…last followed by first…middle (conceptually). Use for array rotation and string problems.


4. Examples

  • Palindrome: compare string with reversed copy or two pointers.
  • Rotate array by k: rotate(begin, end-k, end) pattern.
  • Reverse each word: split or stream words and reverse each.

5. Common pitfalls

  • reverse mutates; use reverse_copy to preserve the original.
  • rotate direction: middle is the element that becomes the new first.
  • Complexity: reverse and rotate are O(n).

Summary

AlgorithmMutates sourceTimeUse
reverseYesO(n)In-place reversal
reverse_copyNoO(n)Keep original
rotateYesO(n)Cyclic shift

Next steps

  • C++ Algorithm Replace
  • C++ Algorithm Count
  • C++ Algorithm Generate

  • C++ Algorithm Copy
  • C++ Algorithm Guide

Keywords

std::reverse, reverse_copy, std::rotate, STL, C++