Solving C++ std::is_permutation Issues: From Performance to Predicates

2025-09-07

First, let's remember what std::is_permutation is all about. It checks if a range [first1, last1) is a permutation of another range [first2, last2). This means it verifies that they contain the exact same elements, with the same frequency, just possibly rearranged.

For example, {1, 2, 3} is a permutation of {3, 1, 2}. On the other hand, {1, 2, 3} is not a permutation of {1, 2, 2} because the element 2 appears with a different frequency.

std::is_permutation doesn't check if the two ranges have the same size. If the sizes are different, the behavior is undefined. This is a common and dangerous trap.

Troubled Code

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

int main() {
    std::vector<int> a = {1, 2, 3};
    std::vector<int> b = {1, 2}; // Different size!

    // This is undefined behavior and might give a wrong result or crash
    if (std::is_permutation(a.begin(), a.end(), b.begin())) {
        std::cout << "They are permutations." << std::endl;
    } else {
        std::cout << "They are not permutations." << std::endl;
    }

    return 0;
}

How to Fix It

Always check the size of the ranges first. This simple check can prevent a lot of headaches.

Corrected Code

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

int main() {
    std::vector<int> a = {1, 2, 3};
    std::vector<int> b = {1, 2};

    if (a.size() != b.size()) {
        std::cout << "The sizes don't match, so they can't be permutations." << std::endl;
    } else if (std::is_permutation(a.begin(), a.end(), b.begin())) {
        std::cout << "They are permutations." << std::endl;
    } else {
        std::cout << "They are not permutations." << std::endl;
    }

    return 0;
}

For very large ranges, std::is_permutation can be slow because it often involves nested loops. A more efficient way to check for a permutation, especially when the element types can be sorted, is to sort both ranges and then compare them directly. This is a great alternative for better performance.

Troubled Code (potentially slow for large data)

// This is not "wrong" but can be slow for large vectors
// The inner workings of std::is_permutation can be O(N^2) in the worst case
// depending on the implementation.
std::vector<int> large_a = { /* a lot of numbers */ };
std::vector<int> large_b = { /* same numbers, shuffled */ };

if (std::is_permutation(large_a.begin(), large_a.end(), large_b.begin())) {
    // ...
}

Alternative
Sort and Compare (Often faster)

If you can modify the original containers or work with copies, sorting is usually a much faster approach. This method has a complexity of O(N log N) due to the sorting, which is typically better than the worst-case O(N^2) of std::is_permutation.

Example

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric> // for std::iota

int main() {
    std::vector<int> a(100000);
    std::iota(a.begin(), a.end(), 1); // Fills with 1 to 100000

    std::vector<int> b = a;
    std::random_shuffle(b.begin(), b.end()); // Shuffle b

    // Alternative approach: sort and compare
    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());

    if (a == b) {
        std::cout << "The two vectors are permutations of each other." << std::endl;
    } else {
        std::cout << "The two vectors are NOT permutations of each other." << std::endl;
    }

    return 0;
}

This method is clean and generally much faster for large datasets.

std::is_permutation uses operator== by default to compare elements. If you have custom data types or need a different comparison logic, you can use a custom predicate.

Example with a custom struct
Let's say you have a struct Item and you want to consider two Items equal if their id is the same, ignoring their value.

Code with a custom comparator

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

struct Item {
    int id;
    std::string value;
};

bool compare_items_by_id(const Item& a, const Item& b) {
    return a.id == b.id;
}

int main() {
    std::vector<Item> a = {{1, "apple"}, {2, "banana"}, {3, "cherry"}};
    std::vector<Item> b = {{2, "grapes"}, {1, "orange"}, {3, "lemon"}};

    // Use a custom comparison function to ignore the `value`
    if (std::is_permutation(a.begin(), a.end(), b.begin(), compare_items_by_id)) {
        std::cout << "The two vectors are permutations based on ID." << std::endl;
    } else {
        std::cout << "The two vectors are NOT permutations based on ID." << std::endl;
    }

    return 0;
}

This is a great feature of std::is_permutation that lets you define exactly what "equal" means for your specific use case.


cpp



Mastering constexpr with std::is_constant_evaluated

The std::is_constant_evaluated function returns true if the current function call is happening within a constant evaluation context


std::basic_regex in C++: Issues and Alternatives

One of the most frequent problems developers run into is with syntax. Regular expression syntax can be quite different from language to language


Complex Arccos in C++ Numerics: Common Gotchas and Code Workarounds

Here's a friendly breakdown of common issues, along with examples and alternative approaches.The std::acos(std::complex) function calculates the complex arc cosine of a given complex number z. Unlike the real-valued acos(x), which is only defined for x∈[−1,1], the complex version is defined for all complex numbers



C++ std::stacktrace_entry: Understanding Common Debugging Issues

The C++ standard library includes a feature for generating stack traces, found in the <stacktrace> header. This feature provides std::stacktrace and std::stacktrace_entry classes


Exploring C++ Ranges: Common Pitfalls with join_with_view and How to Avoid Them

The std::ranges::join_with_view::iterator is a bidirectional iterator that navigates a joined range. A common problem developers face is dealing with its state


Don't Get Stuck! A Practical Look at C++ String Search with find_first_not_of

First, let's quickly recap what find_first_not_of is for. It's a great tool for finding the first character in a string that isn't one of the characters in a specified set


Troubleshooting Predicates in C++

A Predicate is essentially a function or a function object that takes one or more arguments and returns a value that can be contextually converted to bool


Mastering C++ std::thread: Common Pitfalls and Best Practices

A frequent mistake is attempting to swap an active thread with a newly created or detached thread. When you call std::swap(t1


C++ I/O: Demystifying std::istreambuf_iterator

Think of std::istreambuf_iterator as an iterator that reads characters directly from a std::streambuf. This is different from a regular std::istream_iterator


Troubleshooting C++ std::isgraph with std::locale

The C++ function std::isgraph is used to check if a character is a "graphical" character. This includes all printable characters except for the space character