6. (Becoming Acquainted with Callable Objects) In Section 3.5 we introduced five kinds of callable objects that
Question:
6. (Becoming Acquainted with Callable Objects)
In Section 3.5 we introduced five kinds of callable objects that can be used as target methods of std::function<>. The objective here is to write code to compute the inner product of two vectors using each callable object type and then to generalise the notion of inner product to one that takes two vectors as input and that computes a scalar (reduction variable) from them. Answer the following questions:
a) Consider the inner product (also known as scalar product and dot product) of two ndimensional vectors:
u = (u1,…, un)T , v = (v1,…, vn)T , u ⋅ v =
Σn j=1 ujvj.
Write a free function that accepts two std::vector<>instances as input and that produces the quantity described by the above mathematical formula.
b) Write code for the inner product using a function object and a lambda function.
c) Generalise the code so that it operates with other kinds of binary operators (products), for example the distance between two vectors. Three examples are:
l1 distance:
Σn j=1
|uj − vj|
l2 distance:
( Σn j=1
|uj − vj|2
)1∕2 l∞ distance: max 1≤j≤n
|uj − vj|.
Step by Step Answer: