Function Objects

Lab C++ Intermediate 20 points

Write a functor struct InRange { int lo, hi; bool operator()(int x) const; }. Read a range and n numbers, and print those inside the range using copy_if with your functor.

Input

Line 1: lo hi. Then n and n integers.

Output

One line (empty if none).

Example

Input

10 20
6
5 10 15 20 25 12

Output

10 15 20 12
Sample input available Sample output available
Editor
C++

Hints

A class with operator() can be called like a function.

back_inserter appends to a vector.

Solution explanation

Functors carry state (lo, hi) - lambdas with captures are a shorter way to write the same thing.

Show solution
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

struct InRange {
    int lo, hi;
    bool operator()(int x) const { return x >= lo && x <= hi; }
};

int main() {
    int lo, hi, n;
    cin >> lo >> hi >> n;
    vector<int> v(n), out;
    for (int &x : v) cin >> x;
    copy_if(v.begin(), v.end(), back_inserter(out), InRange{lo, hi});
    for (size_t i = 0; i < out.size(); i++) cout << out[i] << (i + 1 < out.size() ? " " : "");
    cout << "\n";
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD