C++ Erase-remove idiom
Retain the stock bins that still contain items to pick.
A simple example
Erase-remove idiom
- Start with 1, 2, 3
- Do this Remove values below 2
- Result 2, 3
Syntax
counts.erase(newEnd, counts.end())
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonClear empty stock bins from the pick list
A stockroom prints only bins that contain items a picker can collect. Empty bins appear twice in today's count, and both should disappear while the remaining quantities keep their order.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> counts{4, 0, 2, 0};
auto end = std::remove(counts.begin(), counts.end(), 0);
counts.erase(end, counts.end());
std::cout << counts.at(0) << ", " << counts.at(1);
return 0;
}
4, 2
Both zeros are excluded and the positive counts stay in order.
Count packs on the delivery slip
A loading desk receives four item counts in sequence. Only positive quantities go to the packing desk. Which entries survive, in their original order?
Review print quantities
A print room records four job quantities, including a cancelled job. Only positive quantities go to the packing desk. Which entries survive, in their original order?
What to watch for
std::remove alone only returns a new logical end. Call erase to shrink the C++17 vector.