Remove values from a list.
What to build
A new vector made from the items that pass a test.
Requirements
- Read the numbers.
- Print the odd numbers in their original order, separated by single spaces.
- Print
noneif there are no odd numbers.
Input
The first line has n. The second line has n whole numbers.
Output
One line.
Constraints
n is from 1 to 1000. Numbers can be negative.
Example
Input:
5
1 2 3 4 5
Output:
1 3 5
Why it works
Building a new list avoids erasing from the middle, which would move the later elements again and again.
Examples
Example 1 · Input
5 1 2 3 4 5
Expected output
1 3 5
Example 2 · Input
2 2 4
Expected output
none
Hints
Hint 1
Build a second vector, and add only the odd numbers.
Hint 2
If it ends up empty, print the special message.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
vector<int> odd;
for (int x : v) {
if (x % 2 != 0) {
odd.push_back(x);
}
}
if (odd.empty()) {
cout << "none" << endl;
} else {
for (int x : odd) cout << x << " ";
cout << endl;
}
return 0;
}