Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to know the algorithm's code to take advantage of inserters and move iterators?

Tags:

c++

c++11

stl

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)?

like image 681
AlwaysLearning Avatar asked Dec 10 '22 22:12

AlwaysLearning


1 Answers

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 the MoveAssignable 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), where ret 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.

like image 182
набиячлэвэли Avatar answered Jun 09 '23 21:06

набиячлэвэли