##Exercise 10.1 and 10.2 ##Exercise 10.3 and 10.4 ##Exercise 10.5 ##Exercise 10.6 ##Exercise 10.7
We said that algorithms do not change the size of the containers over which they operate. Why doesn’t the use of back_inserter invalidate this claim?
Inserters like back_inserter
is part of <iterator>
rather than <algorithm>
.
Why do you think the algorithms don’t change the size of containers?
@Mooophy: The aim of this design is to separate the algorithms and the operation provided by member function.
@pezy: Cause the library algorithms operate on iterators, not containers. Thus, an algorithm cannot (directly) add or remove elements.
##Exercise 10.11 ##Exercise 10.12 ##Exercise 10.13
Write a lambda that takes two ints and returns their sum.
auto add = [](int lhs, int rhs){ return lhs + rhs; };
Write a lambda that captures an int from its enclosing function and takes an int parameter. The lambda should return the sum of the captured int and the int parameter.
int i = 42;
auto add = [i](int num){ return i + num; };
##Exercise 10.16 ##Exercise 10.17 ##Exercise 10.18 and 10.19 ##Exercise 10.20 and 10.21 ##Exercise 10.22
How many arguments does bind take?
Assuming the function to be bound have n
parameters, bind take n + 1
parameters.
The additional one is for the function to be bound itself.
##Exercise 10.24 ##Exercise 10.25
Explain the differences among the three kinds of insert iterators.
back_inserter
usespush_back
.front_inserter
usespush_front
.insert
usesinsert
This function takes a second argument, which must be an iterator into the given container. Elements are inserted ahead of the element denoted by the given iterator.
List the five iterator categories and the operations that each supports.
- Input iterators :
==
,!=
,++
,*
,->
- Output iterators :
++
,*
- Forward iterators :
==
,!=
,++
,*
,->
- Bidirectional iterators :
==
,!=
,++
,--
,*
,->
- Random-access iterators :
==
,!=
,<
,<=
,>
,>=
,++
,--
,+
,+=
,-
,-=
,-
(two iterators),*
,->
,iter[n]
==* (iter + n)
What kind of iterator does a list have? What about a vector?
list
have the Bidirectional iterators. vector
have the Random-access iterators.
What kinds of iterators do you think copy requires? What about reverse or unique?
copy
: first and second are Input iterators, last is Output iterators.reverse
: Bidirectional iterators.unique
: Forward iterators.
Based only on the algorithm and argument names, describe the operation that the each of the following library algorithms performs:
replace(beg, end, old_val, new_val); // replace the old_elements in the input range as new_elements.
replace_if(beg, end, pred, new_val); // replace the elements in the input range which pred is true as new_elements.
replace_copy(beg, end, dest, old_val, new_val); // copy the new_elements which is old_elements in the input range into dest.
replace_copy_if(beg, end, dest, pred, new_val); // copy the new_elements which pred is true in the input range into dest.