C++ std::array::swap: Common Pitfalls & Alternatives

2025-08-26

The std::array::swap method is designed to efficiently exchange the contents of two std::array objects of the same type and size. It performs a member-wise swap of the elements, meaning it swaps each corresponding element of the two arrays.

Unlike some other container swaps, std::array::swap is generally not an O(1) operation. Because std::array is a fixed-size, stack-allocated container, its elements are swapped one by one. The complexity is linear, O(N), where N is the number of elements in the array.

A frequent mistake is trying to swap two std::array objects that don't have the same element type or size. This will result in a compilation error. The compiler won't let you perform this operation because the arrays are fundamentally incompatible.

Problem Code

#include <array>
#include <iostream>

int main() {
    std::array<int, 3> arr1 = {1, 2, 3};
    std::array<double, 3> arr2 = {4.0, 5.0, 6.0};
    
    // This will cause a compilation error!
    // 'arr2' is a different type.
    // arr1.swap(arr2); 
    
    // This will also cause a compilation error!
    // 'arr3' is a different size.
    std::array<int, 2> arr3 = {7, 8};
    // arr1.swap(arr3);
    
    return 0;
}

The Fix

The solution is simple
ensure both arrays have the exact same template parameters—the same type and the same size.

#include <array>
#include <iostream>

int main() {
    std::array<int, 3> arr1 = {1, 2, 3};
    std::array<int, 3> arr2 = {4, 5, 6};
    
    // This is correct because both arrays are std::array<int, 3>
    arr1.swap(arr2);
    
    std::cout << "arr1 after swap: " << arr1[0] << ", " << arr1[1] << ", " << arr1[2] << std::endl; // Output: 4, 5, 6
    std::cout << "arr2 after swap: " << arr2[0] << ", " << arr2[1] << ", " << arr2[2] << std::endl; // Output: 1, 2, 3
    
    return 0;
}

For std::array, using std::swap from the <utility> or <algorithm> header is often a more idiomatic and flexible approach. The general std::swap function will automatically choose the most efficient swap method available, which for std::array will be its member swap function.

The non-member std::swap is the preferred method in modern C++ because it works consistently across all standard containers and types that support swapping.

Example Code
Using std::swap

#include <array>
#include <iostream>
#include <utility> // For std::swap

int main() {
    std::array<int, 3> arr1 = {10, 20, 30};
    std::array<int, 3> arr2 = {40, 50, 60};

    std::cout << "Before swap:" << std::endl;
    std::cout << "arr1: " << arr1[0] << ", " << arr1[1] << ", " << arr1[2] << std::endl;
    std::cout << "arr2: " << arr2[0] << ", " << arr2[1] << ", " << arr2[2] << std::endl;

    // Use the non-member std::swap
    std::swap(arr1, arr2);

    std::cout << "\nAfter swap:" << std::endl;
    std::cout << "arr1: " << arr1[0] << ", " << arr1[1] << ", " << arr1[2] << std::endl; // Output: 40, 50, 60
    std::cout << "arr2: " << arr2[0] << ", " << arr2[1] << ", " << arr2[2] << std::endl; // Output: 10, 20, 30

    return 0;
}

Why is std::swap a better choice?

Consistency
You can use std::swap for std::vector, std::deque, std::list, and std::array without having to remember the specific member function for each.

Flexibility
It's the standard way to swap objects in C++ and works for user-defined types as well, as long as a suitable swap function is available.

If for some reason you can't or don't want to use swap, you can always manually swap the elements one by one. This is functionally what std::array::swap does internally, but it's more verbose and error-prone. It's generally not recommended.

Example Code
Manual Swap

#include <array>
#include <iostream>
#include <utility> // For std::swap

int main() {
    std::array<int, 3> arr1 = {100, 200, 300};
    std::array<int, 3> arr2 = {400, 500, 600};

    // Manual swap using a loop
    for (size_t i = 0; i < arr1.size(); ++i) {
        std::swap(arr1[i], arr2[i]);
    }
    
    std::cout << "arr1 after manual swap: " << arr1[0] << ", " << arr1[1] << ", " << arr1[2] << std::endl; // Output: 400, 500, 600
    std::cout << "arr2 after manual swap: " << arr2[0] << ", " << arr2[1] << ", " << arr2[2] << std::endl; // Output: 100, 200, 300

    return 0;
}

cpp



C++ std::system_error::operator=: Common Issues & Alternatives

First off, it's good to understand what std::system_error is. It's an exception class in C++ that's used to report errors from the operating system or other low-level APIs


How to Correctly Use std::chrono::operator== for Temporal Comparisons

One of the most frequent issues developers encounter with std::chrono is type mismatch. The operator== you're asking about has a very specific signature it compares a std::chrono::weekday with a std::chrono::weekday_indexed


Mastering std::recursive_mutex::lock: Common Pitfalls and Solutions

std::recursive_mutex is a synchronization primitive in C++ designed to solve a very specific problem recursive locking. Unlike a standard std::mutex



std::flat_set::max_size() Pitfalls and Alternatives

The std::flat_set::max_size() method returns the maximum number of elements a flat set can hold. This value is determined by the system's available memory and the specific container's implementation


Reader-Writer Locks in C++: A Guide to std::shared_lock

When you're dealing with concurrent programming, it's common to have multiple threads that need to access the same resource


The C++ weak_ptr owner_hash Explained: Use Cases and Compiler Compatibility

First off, let's get acquainted with std::weak_ptr::owner_hash itself.std::weak_ptr::owner_hash is a C++ feature introduced in C++26


C++ std::fgetpos Explained: Pitfalls and fstream Solutions

std::fgetpos is a function from the <cstdio> header, which is part of the C standard library. It's used to get the current file position of a stream


Troubleshooting C++ std::basic_filebuf::seekoff()

It's a versatile function, but it can sometimes be tricky to use, especially if you're not familiar with file handling in C++. Here's a look at some common pitfalls and how you can work around them


Mastering C++ Ranges: Solving Common stride_view Issues

One of the most frequent issues developers face is with off-by-one errors when setting the stride. A stride of 1 means you're moving one step at a time


C++ std::string_view: A Guide to operator= and Common Pitfalls

The operator= for std::basic_string_view is used to assign a new view to an existing one. It's a quick and simple way to make the string_view point to a different sequence of characters