C++ Primer (5th edition) gives a number of examples of achieving nice effects by passing an inserter
or a move iterator
instead of a regular iterator into an std
's generic algorithm.
I suspect, however, that being able to do this depends on inside knowledge of the workings of the algorithm, i.e. what precisely it does with its iterator arguments. This is even more severe with the move inserter
, since we need to be sure that an object is not accessed after being moved from.
Is my suspicion justified? If it is, then how come the standard library takes an approach that requires the client (me) to know the internals of the provider (STL)?
No, you don't need to know the implememtation of any of the STL algorithms, as they have their Requirements in general specified in The International Standard.
For example, std::remove()
is declared as:
template<class ForwardIterator, class T>
ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value);
And is described as follows:
template<class ForwardIterator, class T>
ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value);
- Requires: The type of
*first
shall satisfy theMoveAssignable
requirements (Table 22).- Effects: Eliminates all the elements referred to by iterator
i
in the range[first,last)
for which the following corresponding conditions hold:*i == value
.- Returns: The end of the resulting range.
- Remarks: Stable (17.6.5.7).
- Complexity: Exactly
last - first
applications of the corresponding predicate.- Note: each element in the range
[ret,last)
, whereret
is the returned value, has a valid but unspecified state, because the algorithms can eliminate elements by moving from elements that were originally in that range.
So all you ever need to know is The International Standard's paragraph about the algorithm, as it (and only it) specifies exactly what happens in the particular algorithm, no more, no less.
Besides, reading STL internals is a not a good idea, most of the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With