Write a lambda function to check if a number can be divided by the first input n
ID: 652748 • Letter: W
Question
Write a lambda function to check if a number can be divided by the first input number (assume there are at least 2 input numbers). Using the count_if function (from the algorithm header, see this link for more details:
http://www.cplusplus.com/reference/algorithm/count_if/), check how many such numbers are there in a user inputs and output the number of such values.
Furthermore, you will need to write a function object that checks if a number is greater than 8. You will then use the find_if function (from the algorithm header, see this link for more details: http://www.cplusplus.com/reference/algorithm/find_if/), to find the first required value in the same range. In addition, if there is no such value in the input, you should also indicate it. Since we are doing C++ functional programming, please create a class named "isGreater" to implement this function object.
Here is a sample run of the program:
About function pobject, just overload operator "()".
class isGreater{
public:
bool operator () (int value){
// do something here
}
};
Sample Run:
./lab11
Enter numbers to check:
5 2 7 10 3 6 8 15 d
There are 3 numbers that can be divided by 5.
The first element greater than 8 is 10.
./lab11
Enter numbers to check:
3 1 2 3 4 5 6 7 d
There are 3 numbers that can be divided by 3.
There is no element greater than 8!
Explanation / Answer
Answer:
#include <iostream>
#include <algorithm>
#include <vector>
int a[10];
bool IsOdd (int i) { return ((a[i]/a[1])==0); }
bool IsOdd1 (int i) { return (a[i]>8); }
int main () {
std::vector<int> myvector;
for (int i=1; i<3; i++) {
std::cin >> a[i];
myvector.push_back(a[i]); // myvector: 1 2 3 4 5 6 7 8 9
}
int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "There are " << mycount<<" numbers that can be divided by "<<a[1]<<' ';
std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd1);
std::cout << "The first element greater by 8 is " << *it << ' ';
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.