Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::rotate

Use case

Rotate elements so that a given element becomes the first.

Explanation

Left rotation: elements before middle move to end. Use rotate_copy for non-modifying version. Returns iterator to original first element’s new position.

Time complexity: O(n). Each element is moved once. See possible implementation.

Code

#include <algorithm>
#include <print>
#include <string>
#include <vector>

int main() {
  // https://100daysofredteam.medium.com/mach-o-file-format-for-red-team-professionals-fb89ea6c311e
  std::vector<std::string> loadCommands = {"LC_SEGMENT_64 (__TEXT)",
                                           "LC_SEGMENT_64 (__DATA)", "LC_MAIN",
                                           "LC_SEGMENT_64 (__LINKEDIT)"};

  auto mainIt = std::find(loadCommands.begin(), loadCommands.end(), "LC_MAIN");

  if (mainIt != loadCommands.end()) {
    std::rotate(loadCommands.begin(), mainIt, loadCommands.end());
  }

  std::println("Rotated load commands:");
  for (const auto &lc : loadCommands) {
    std::println("{}", lc);
  }

  return 0;
}

View on GitHub.

Output

$ ./src/algorithms/build/std-rotate
Rotated load commands:
LC_MAIN
LC_SEGMENT_64 (__LINKEDIT)
LC_SEGMENT_64 (__TEXT)
LC_SEGMENT_64 (__DATA)