C++ Primer(第 5 版)给出了一些通过传递 inserter
或 move iterator
而不是std
的通用算法的常规迭代器。
但是,我怀疑能否做到这一点取决于对算法工作原理的内部知识,即算法对其迭代器参数的精确处理。这对于 move inserter
来说更加严重,因为我们需要确保对象在被移动之后不会被访问。
我的怀疑有道理吗?如果是,那么标准库为何采用要求客户端(我)了解提供程序 (STL) 内部结构的方法?
最佳答案
不,您不需要了解任何 STL 算法的实现,因为它们在国际标准中有一般规定的要求。
例如,std::remove()
声明为:
template<class ForwardIterator, class T>
ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value);
并说明如下:
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.
因此,您需要知道的就是国际标准中关于算法的段落,因为它(并且只有它)明确指定了特定算法中发生的什么,不更多,不少。
此外,在大多数情况下,阅读 STL 内部结构并不是一个好主意。
关于c++ - 我是否需要知道算法的代码才能利用插入器和移动迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31586277/