17.7 Introduction to Function Objects and Lambda Expressions 1107 Checkpoint eno
ID: 3724316 • Letter: 1
Question
17.7 Introduction to Function Objects and Lambda Expressions 1107 Checkpoint enoted by twO hat does the first 17.38 What must you do to a range of elements before searching it with the binary If the elements that you are sorting with the sort () function contain your own class objects, you must be sure that the class overloads what operator? 17.39 Assume vect is a vector that contains 100 int elements, and the following statement appears in a program: 17.42 for_each(vect.begin(), vect.end() myFunction) Without knowing anything else about the program, answer the following questions: A) What is myFunction? B) How many arguments does myFunction accept? What are the data type(s) of the argument(s)? C) What value does myFunction return? D) How many times will the statement cause myFunction to be called?Explanation / Answer
class MyData
int m_iData;
string m_strSomeOtherData;
bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
std::sort(myvector.begin(), myvector.end());
3.
a. myFunction() should be a function that will be applied to all the vector elements.The template is shown below:
for_each(InputIterator first, InputIterator last, Function f)
first, last
Input iterators to the initial and final positions in a sequence. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
f
Unary function taking an element in the range as argument. This can either be a pointer to a function or an object whose class overloads operator().Its return value, if any, is ignored.
Let’s look at the following example:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void myfunction (int i) {
cout << " " << i;
}
struct myclass {
void operator() (int i) {cout << " " << i;}
} myobject;
int main () {
vector<int> myvector;
myvector.push_back(10);
myvector.push_back(20);
myvector.push_back(30);
cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myfunction);
// or:
cout << " myvector contains:";
for_each (myvector.begin(), myvector.end(), myobject);
cout << endl;
return 0;
}
b. As shown it the above example, myFunction() can take one argument of int datatype.
c. myFunction() return type is void;
d. Assuming we have 100 elements, it will be called 100 times.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.