C++: Remove one occurrence from a multiset
A multiset can track repeated inventory values. When one item is consumed, erase the iterator returned by find; erasing by key would remove every equivalent occurrence.
Prepare a scratch directory
Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. 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 as cpp-multiset-erase-one-occurrence.cpp:
#include <cassert>
#include <iostream>
#include <set>
bool consume_one(std::multiset<int>& stock, int value) {
const auto found = stock.find(value);
if (found == stock.end()) return false;
stock.erase(found);
return true;
}
int main() {
std::multiset<int> stock{4, 4, 4, 9};
const bool consumed = consume_one(stock, 4);
assert(consumed);
if (!consumed) return 1;
assert(!consume_one(stock, 7));
std::cout << "remaining 4s: " << stock.count(4) << '\n';
for (int value : stock) std::cout << ' ' << value;
std::cout << '\n';
std::multiset<int> empty;
assert(!consume_one(empty, 4));
}Compile and run:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-multiset-erase-one-occurrence.cpp -o cpp-multiset-erase-one-occurrence &&
./cpp-multiset-erase-one-occurrenceObserved output:
remaining 4s: 2
4 4 9How it works
The lookup either finds one equivalent element or returns end(). The guard prevents passing that past-the-end iterator to erase. With three copies of 4, one call leaves two. The missing-key path changes nothing.
Limits and choices
Equivalence follows the container comparator. For records ordered by only one field, find does not select a particular record among equivalent entries. Use an additional identifier when the identity of the removed record matters. References to the erased element become invalid; references to other elements remain valid.
The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.
Clean up
rm -- cpp-multiset-erase-one-occurrence.cpp cpp-multiset-erase-one-occurrence
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect the remaining files before removing anything else.
Acknowledgements
This post was created with assistance from AI.