Erase-Remove Idiom
Completed
Read n integers and remove all negative numbers using remove_if + erase. Print the remaining numbers (or empty).
Input
Line 1: n. Line 2: n integers.
Output
One line.
Example
Input
6 3 -1 4 -1 -5 9
Output
3 4 9
Editor
C++
Hints
remove_if moves the kept items to the front and returns the new logical end.
erase then deletes the leftover tail.
Solution explanation
This two-step erase-remove idiom is the standard way to delete by condition before C++20.
Show solution
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int &x : v) cin >> x;
v.erase(remove_if(v.begin(), v.end(), [](int x) { return x < 0; }), v.end());
if (v.empty()) cout << "empty";
for (size_t i = 0; i < v.size(); i++) cout << v[i] << (i + 1 < v.size() ? " " : "");
cout << "\n";
return 0;
}