(C++) Answer of exercise \#8: Library trouble \#0

February 24, 2017 · View on GitHub

 

 

 

 

 

(C++) Answer of exercise #8: Library trouble #0

 

This is the answer of Exercise #8: library trouble.

 

The compiler takes you to the following code:

 


// search_n. Search for __count consecutive copies of __val. template <class _ForwardIter, class _Integer, class _Tp>   _ForwardIter search_n(_ForwardIter __first, _ForwardIter __last,   _Integer __count, const _Tp& __val) {   _STLP_DEBUG_CHECK(__check_range(__first, __last))   if (__count <= 0)     return __first;   else {     __first = find(__first, __last, __val);     while (__first != __last) {       _Integer __n = __count - 1;       _ForwardIter __i = __first;       ++__i;       while (__i != __last && __n != 0 && *__i == __val) {         ++__i;         --__n; // <---- THIS LINE       }       if (__n == 0)         return __first;       else         __first = find(__i, __last, __val);       }     return __last;   } }

 

This must means that __n is also a const data type. This is true, as shown below:

 


// search_n. Search for __count consecutive copies of __val. template <class _ForwardIter, class /*non-const*/ _Integer, class _Tp>   _ForwardIter search_n(_ForwardIter __first, _ForwardIter __last,   /*non-const*/ _Integer __count, const _Tp& __val) {   _STLP_DEBUG_CHECK(__check_range(__first, __last))   if (__count <= 0)     return __first;   else {     __first = find(__first, __last, __val);     while (__first != __last) {       /*non-const*/ _Integer __n = __count - 1;       _ForwardIter __i = __first;       ++__i;       while (__i != __last && __n != 0 && *__i == __val) {         ++__i;         --__n; // <---- THIS LINE       }       if (__n == 0)         return __first;       else         __first = find(__i, __last, __val);       }     return __last;   } }

 

So, due to the template use, __n will be of type const int, when we pass a __count of type const int! This conflict with the use of __n as a changing index. The type of __n should be the non-const type of __count.