C++ Basics: Check That a Sorted Inventory Covers Required Counts
Use std::includes to test sorted requirements while respecting repeated values.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as includes-required-counts-demo.cpp:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
const std::vector<int> stock{1, 2, 2, 4};
const std::vector<int> enough{2, 2};
const std::vector<int> too_many{2, 2, 2};
const std::vector<int> empty;
std::cout << std::boolalpha;
std::cout << "Two copies: " << std::includes(stock.begin(), stock.end(), enough.begin(), enough.end()) << '\n';
std::cout << "Three copies: " << std::includes(stock.begin(), stock.end(), too_many.begin(), too_many.end()) << '\n';
std::cout << "No requirements: " << std::includes(stock.begin(), stock.end(), empty.begin(), empty.end()) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic includes-required-counts-demo.cpp -o includes-required-counts-demo &&
./includes-required-counts-demoObserved output:
Two copies: true
Three copies: false
No requirements: trueRead the result
Two requested copies of 2 are covered, but three are not. An empty requirement list is satisfied. The test checks containment with multiplicity and leaves both input sequences unchanged.
Apply it carefully
Both ranges must be sorted using the comparison supplied to includes. A single binary_search only proves that a key exists, not that enough copies exist. This function returns a boolean rather than a shortage report. Keep separate validation if you need to explain which quantities are missing, and do not treat this read-only check as a concurrent reservation of inventory.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- includes-required-counts-demo.cpp includes-required-counts-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.