A Guide to std::stable_partition in C++: Examples and Tips

2025-09-23

The std::stable_partition algorithm is a powerful tool in the C++ Standard Library. Its job is to rearrange elements in a range so that all elements satisfying a certain condition (a predicate) come before all elements that don't. The key thing that makes it "stable" is that it preserves the relative order of elements within each of the two partitions.

For example, if you have a list of numbers [1, 5, 2, 8, 3] and you want to partition it by whether the number is even, a stable partition would result in something like [2, 8, 1, 5, 3]. Notice how 2 still comes before 8 and 1 still comes before 5 and 3. An unstable partition (like std::partition) might rearrange things and give you [8, 2, 1, 3, 5], which is still correct but doesn't maintain the original relative order.

std::stable_partition returns an iterator to the first element of the second group (the elements that didn't satisfy the condition).

Here's a simple example of how you'd use it

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

bool is_even(int n) {
    return n % 2 == 0;
}

int main() {
    std::vector<int> numbers = {1, 4, 3, 6, 5, 2};
    
    // Partition the vector
    std::stable_partition(numbers.begin(), numbers.end(), is_even);
    
    // Print the result
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    // Expected output: 4 6 2 1 3 5
    
    return 0;
}

Even though std::stable_partition is straightforward, a few common issues can trip you up.

This is a very common mistake! The algorithm rearranges the elements in place, but it also returns an iterator. This return value is crucial because it marks the boundary between the two partitions. You need it if you want to perform operations on just one of the groups.

The Problem

You've partitioned the container but don't know where the first group ends.

The Fix (Example)

Store the returned iterator and use it as the end of the first partition.

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

bool is_odd(int n) {
    return n % 2 != 0;
}

int main() {
    std::vector<int> numbers = {1, 4, 3, 6, 5, 2};
    
    // Store the iterator to the partition point
    auto partition_point = std::stable_partition(numbers.begin(), numbers.end(), is_odd);
    
    // Now you can easily print just the odd numbers
    std::cout << "Odd numbers: ";
    for (auto it = numbers.begin(); it != partition_point; ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    
    // Print the even numbers
    std::cout << "Even numbers: ";
    for (auto it = partition_point; it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    // Expected output:
    // Odd numbers: 1 3 5 
    // Even numbers: 4 6 2
    
    return 0;
}

std::stable_partition is not as fast as std::partition. The "stable" part of the name comes with a cost, as the algorithm often requires extra memory or more complex logic to maintain the relative order. It's usually implemented in a way that minimizes extra memory, but the performance can be worse, especially for large containers.

The Problem

Your program is running slower than expected, and you don't actually need the relative order to be preserved.

The Fix (Alternative)

If you don't care about the relative order of elements, use std::partition instead. It's often significantly faster and is the default choice unless you specifically need stability.

Example (Using std::partition)

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

bool is_even(int n) {
    return n % 2 == 0;
}

int main() {
    std::vector<int> numbers = {1, 4, 3, 6, 5, 2};
    
    // Using the faster but unstable partition
    std::partition(numbers.begin(), numbers.end(), is_even);
    
    // The output could be something like: 2 4 6 1 5 3
    // The relative order of 2, 4, 6 and 1, 5, 3 is not guaranteed.
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

What if std::stable_partition isn't quite what you need, or you're trying to achieve something similar in a different way?

If you don't want to modify the original container or are simply trying to get two separate lists of elements, you can use std::copy_if to filter the elements into new containers.

Example

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator> // for std::back_inserter

bool is_even(int n) {
    return n % 2 == 0;
}

int main() {
    std::vector<int> numbers = {1, 4, 3, 6, 5, 2};
    std::vector<int> evens;
    std::vector<int> odds;

    // Copy even numbers to the 'evens' vector
    std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(evens), is_even);

    // Copy odd numbers to the 'odds' vector
    std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(odds), [](int n){ return n % 2 != 0; });
    
    std::cout << "Original vector remains unchanged." << std::endl;
    std::cout << "Evens: ";
    for (int n : evens) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    
    std::cout << "Odds: ";
    for (int n : odds) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

This approach is great for read-only operations and creating new, sorted-by-condition lists without modifying the original.

Sometimes, the most readable and flexible solution is just a simple for loop. This gives you complete control over the logic, though it might be more verbose.

Example

#include <iostream>
#include <vector>

bool is_even(int n) {
    return n % 2 == 0;
}

int main() {
    std::vector<int> numbers = {1, 4, 3, 6, 5, 2};
    std::vector<int> evens;
    std::vector<int> odds;

    for (int n : numbers) {
        if (is_even(n)) {
            evens.push_back(n);
        } else {
            odds.push_back(n);
        }
    }

    std::cout << "Evens (manual loop): ";
    for (int n : evens) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    
    std::cout << "Odds (manual loop): ";
    for (int n : odds) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    return 0;
}

This is a great option when the logic is simple and you need to perform actions on the elements as you categorize them, not just copy them.


cpp



Handling std::regex_error in C++: A Practical Guide

This is the most frequent cause of std::regex_error. A small typo or an incorrect use of a special character can lead to this error


Debugging with C++: A Guide to std::basic_stacktrace::operator= and Beyond

The operator= is used for assignment, and it typically doesn't cause many problems on its own. The issues you're more likely to see are related to the object being copied from or the context in which the assignment happens


Deep Dive into C++ Diagnostics: When and How to Use native_handle()

In simple terms, std::stacktrace_entry::native_handle() returns an implementation-defined native handle for a single entry (or frame) in a stack trace



C++ Concurrency: A Guide to std::atomic

Hey there! Let's talk about std::atomic in C++. It's a key feature for concurrency, which is when multiple parts of a program run at the same time


Beyond std::pair: When to Use Structs and Tuples in C++

One of the most frequent issues is making unnecessary copies of std::pair objects. This can be a big problem, especially if your pairs contain large objects


C++ std::wmemcmp Explained: A Guide to Raw Memory Comparison

First off, let's understand what this function does. std::wmemcmp is a C-style function in C++ used for a raw memory comparison of two wide-character arrays


Safe Alternatives to std::exit in C++

The std::exit function is used to terminate a C++ program immediately. When you call std::exit, it performs cleanup tasks like flushing output streams (like std::cout) and running functions registered with std::atexit


A Developer's Guide to Using std::any and Smart Pointers

First, let's quickly review what std::any is. It's a type-safe container that can hold a value of any single type. The ~any part refers to its destructor


Common Issues and Solutions for std::set Deduction Guides in C++

First, let's quickly explain what deduction guides are. They're a modern C++ feature that allows the compiler to automatically deduce the template arguments for a class template from the arguments passed to its constructor


Beyond size(): A Look at std::ranges::ssize and Its Use Cases

While std::ranges::ssize is designed to be safer, developers still run into a few common issues, mainly related to type mismatches and incorrect usage with certain range types