c++ - 我是否需要知道算法的代码才能利用插入器和移动迭代器?

标签 c++ c++11 stl

C++ Primer(第 5 版)给出了一些通过传递 insertermove 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 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.

因此,您需要知道的就是国际标准中关于算法的段落,因为它(并且只有它)明确指定了特定算法中发生的什么,不更多,不少。

此外,在大多数情况下,阅读 STL 内部结构并不是一个好主意。

关于c++ - 我是否需要知道算法的代码才能利用插入器和移动迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31586277/

相关文章:

c++ - 向条件语句添加条件

c++ - 对指针列表进行排序

c++ - 检测是否按下了 QScrollBar 的箭头按钮

c++ - 如何使用 va_list 解决错误?

C++ vector 数学和 OpenGL 兼容

c++ - 我怎样才能用阻塞写入cout?

c++ - const 迭代器依赖于 begin() 函数

c++ - 从文件中读取输入并填充数组以存储数据供以后使用

C++ STL pop 不返回

c++ - 真的对 map::erase() 感到困惑