Sorting Out std::ranges::includes: A Guide to Common Problems

2025-09-15

std::ranges::includes is fantastic for checking if one range contains all the elements of another, but a few common pitfalls can trip you up.

std::ranges::includes assumes both ranges are already sorted. If they aren't, the result is undefined, which often leads to incorrect output. This is a very common mistake.

Problematic Code Example

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

int main() {
    std::vector<int> main_vec = {1, 5, 2, 4, 3};
    std::vector<int> sub_vec = {2, 3};

    if (std::ranges::includes(main_vec, sub_vec)) {
        std::cout << "The main vector includes the sub-vector.\n";
    } else {
        std::cout << "The main vector does not include the sub-vector.\n";
    }
    return 0;
}

In this example, main_vec is not sorted, so std::ranges::includes will likely return false even though it should be true.

Solution
Sort the Ranges First Before calling std::ranges::includes, make sure both ranges are sorted. You can use std::ranges::sort for this.

Corrected Code Example

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

int main() {
    std::vector<int> main_vec = {1, 5, 2, 4, 3};
    std::vector<int> sub_vec = {2, 3};

    std::ranges::sort(main_vec);
    std::ranges::sort(sub_vec);

    std::cout << "Sorted main vector: ";
    for (int x : main_vec) std::cout << x << " ";
    std::cout << "\n";

    std::cout << "Sorted sub vector: ";
    for (int x : sub_vec) std::cout << x << " ";
    std::cout << "\n";

    if (std::ranges::includes(main_vec, sub_vec)) {
        std::cout << "The main vector includes the sub-vector.\n"; // This will now be correct!
    } else {
        std::cout << "The main vector does not include the sub-vector.\n";
    }
    return 0;
}

Sometimes people confuse std::ranges::includes with finding a contiguous subsequence (a part of the range that is next to each other, like 2, 3, 4 in 1, 2, 3, 4, 5). However, std::ranges::includes checks for all elements, not necessarily in a contiguous block.

Incorrect Use Case
Let's say you want to find {3, 4} in {1, 2, 3, 4, 5}. While std::ranges::includes will find it, it's not the right tool for finding a contiguous subsequence.

Better Alternative
std::ranges::search For finding a contiguous subsequence, std::ranges::search is the perfect tool. It's designed specifically for this purpose and doesn't require sorted ranges. It returns an iterator to the start of the found subsequence or to the end of the range if it's not found.

std::ranges::search Code Example

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

int main() {
    std::vector<int> main_vec = {1, 2, 3, 4, 5};
    std::vector<int> sub_vec = {3, 4};

    auto result = std::ranges::search(main_vec, sub_vec);

    if (!result.empty()) {
        std::cout << "Found contiguous subsequence starting at index: " << std::distance(main_vec.begin(), result.begin()) << "\n";
    } else {
        std::cout << "Subsequence not found.\n";
    }
    return 0;
}

If std::ranges::includes isn't quite right for your situation, here are a couple of powerful alternatives.

If you just want to know if every element in sub_vec is present somewhere in main_vec, regardless of order or duplication, you can use a combination of a hash set (std::unordered_set) and std::ranges::all_of. This is a very flexible and often fast approach.

Code Example using std::unordered_set

#include <iostream>
#include <vector>
#include <unordered_set>
#include <ranges>
#include <algorithm>

int main() {
    std::vector<int> main_vec = {10, 2, 50, 4, 30};
    std::vector<int> sub_vec = {4, 10};

    // Create a hash set from the main vector for quick lookups
    std::unordered_set<int> main_set(main_vec.begin(), main_vec.end());

    // Check if all elements of sub_vec exist in the hash set
    auto includes_all = std::ranges::all_of(sub_vec, [&](int val) {
        return main_set.count(val) > 0;
    });

    if (includes_all) {
        std::cout << "All elements of the sub-vector are present.\n";
    } else {
        std::cout << "Not all elements of the sub-vector are present.\n";
    }
    return 0;
}

This approach is particularly good because it has an average time complexity of O(N+M) where N and M are the sizes of the ranges, which can be much faster than sorting large ranges first.


cpp



Swapping Tuples in C++: A Guide to std::swap

The std::swap function is a great tool for exchanging the values of two objects. When you use it with std::tuple, it efficiently swaps the elements of two tuples of the same type and size


Troubleshooting C++ std::charconv: Common Issues and Solutions

std::charconv is a great C++ header for efficient string-to-number and number-to-string conversions. It's designed to be fast


Why std::regex_match Isn't Working and What to Use Instead

std::regex_match is a great tool for checking if a whole string matches a regular expression. However, it can be a bit tricky



Mastering std::unique_copy: Common Problems and Solutions

The most frequent issue is expecting std::unique_copy to remove all duplicates in a range, even if they aren't adjacent


C++ std::terminate_handler: A Guide to Custom Error Handling

In C++, an exception is a way to signal and handle errors gracefully. However, sometimes an exception can't be handled. When that happens


The C++ Reader-Writer Timed Lock: try_lock_shared_for Explained

Here's a friendly breakdown of this function, common pitfalls, and some alternative approaches.This function is part of C++'s "Reader-Writer Lock" mechanism


C++17 Attributes: A Guide to [[maybe_unused]] and Alternatives

Here is a friendly, detailed explanation of its purpose, common pitfalls, and examples of alternative approaches.The [[maybe_unused]] attribute


Why std::bitset Size Must Be a Compile-Time Constant

std::bitset is a template class, and its size is determined at compile time. This is a major point to remember. The size


A Guide to C++ Ranges: Understanding sentinel with elements_view

First, let's quickly recap what a sentinel is. In the context of C++ ranges, a sentinel is a type that can be compared to an iterator to determine the end of a range


Exploring std::deque::empty(): Common Issues & Alternatives

At its core, std::deque::empty() is a member function of the std::deque container. Its job is simple it checks if the deque is empty