Movement Algorithms

Implementing a Custom Swap Function

How can you implement a custom swap() function to optimize standard library algorithms?

Abstract art representing computer programming

Implementing a custom swap() function can optimize standard library algorithms such as std::ranges::reverse(), especially if your type has specific requirements or optimizations for swapping elements. Here's how you can do it:

Custom swap Function

First, define your custom type and implement the swap function:

#include <algorithm>
#include <iostream>
#include <vector>

struct Player {
  std::string name;
  int score;

  Player(std::string n, int s)
    : name(n), score(s) {}

  // Custom swap function
  friend void swap(Player& a, Player& b) {
    std::cout << "Swapping " <<
      << " with " << << "\n";
    std::swap(a.score, b.score);

int main() {
  std::vector<Player> players{
    {"Alice", 30}, {"Bob", 20}, {"Charlie", 40}


  for (const auto& player : players) {
    std::cout << << ": "
      << player.score << "\n";
Swapping Alice with Charlie
Charlie: 40
Bob: 20
Alice: 30

How It Works

  1. Define the Custom Type: We created a Player struct with a name and score.
  2. Implement the swap() function: The swap() function swaps the name and score of two Player objects. Note the use of std::swap() within the custom swap().
  3. Call the std::ranges::reverse() Algorithm: : When std::ranges::reverse() is called, it uses the custom swap() function to swap elements.


  • Optimization: Custom swap logic can be more efficient than the default std::swap(), especially if the type has complex move semantics.
  • Debugging: Adding print statements in the swap() function helps in debugging by showing when and how elements are swapped.

Practical Example

Here's another example with a more complex type:

#include <algorithm>
#include <iostream>
#include <vector>

struct ComplexType {
  int data[100];

  friend void swap(ComplexType& a, ComplexType& b) {
    std::cout << "Swapping ComplexType objects\n";
    for (int i = 0; i < 100; ++i) {

int main() {
  std::vector<ComplexType> vec(2);
Swapping ComplexType objects


Implementing a custom swap() function allows you to tailor the swapping behavior to your specific type, which can optimize operations like std::ranges::reverse().

This is especially useful for types that have complex or costly move operations, ensuring efficient and correct element manipulation.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved