6. (C++11 and STL Algorithms) In Section 4.4.1 we discussed how to extend STL algorithms using a...
Question:
6. (C++11 and STL Algorithms)
In Section 4.4.1 we discussed how to extend STL algorithms using a number of features in C++. The objective of this exercise is to analyse and review the code to compute the inner product of two containers containing arithmetic data.
Answer the following questions:
a) Modify the code to check that the instantiated data is arithmetic. Use static_assert and the trait std::is_arithmetic (we discuss type traits in detail in Chapter 6).
b) We used the template–template parameter trick in Section 4.4.1 to allow us to define an algorithm that works with a range of generic containers. The STL specification on the other hand is:
template< class InputIt1, class InputIt2, class T >
T inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T value);
Compare these contrasting approaches with regard to understandability, robustness and extendibility. For example, we may wish to parallelise the code or to introduce code to reduce round-off errors.
c) STL implements a generalised algorithm to compute the inner product of two vectors;
an example is:
// Using two predefined function objects using inner and outer
// operations std::vector
int ip2 = std::inner_product(
std::begin(vecInt), std::end(vecInt), std::begin(vecInt), 1, std::multiplies
d) Test the code in Section 4.4 with a variety of data types (int, float, double), containers (std::vector, std::list) and default input arguments to the function InnerProduct. What happens if you try to compute the inner product of two string containers?
Step by Step Answer: