STL源码剖析笔记-6算法(6.4 基本算法)

来源:互联网 发布:webstorm 调试js 编辑:程序博客网 时间:2024/06/06 06:33

6.4 基本算法

  • 基本算法位于头文件<stl_algobase.h>
  • equal:判断两个序列是否相等
    • 要求第二个序列要比第一个序列多。
template <class InputIterator1, class InputIterator2>inline bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2)
  • fill:将序列内的元素改填新值。
template <class ForwardIterator, class T>void fill(ForwardIterator first, ForwardIterator last, const T& value)
  • fill_n:将序列内的前n个元素改填新值;返回的迭代器指向最后一个填入的元素的下一位置。
    • 要求操作区间不能超越容器的大小,否则就要使用有插入功能的迭代器如inserter().
template <class OutputIterator, class Size, class T>OutputIterator fill_n(OutputIterator first, size n, const T& value)
  • iter_swap:交换两个迭代器所指的对象。
    • 使用value_type()可以获取迭代器的类型
template <class ForwardIterator1, class ForwardIterator2>inline void iter_swap(ForwardIterator1 a, ForwardIterator2 b)
  • lexicographical_compare:以字典排列方式比较两个序列
    • 第一个序列较小时返回true
    • 所有元素都匹配返回false
    • 匹配到最后时,第一列如果短,返回true
    • 注意:大写字母的ADCII码小于小写字母。
template <class InputIterator1, class InputIterator2>bool lexicographical_compare(InputIterator1 first1, Inuterator1 last1, Inuterator2 first2, Inuterator2 last2)
  • max:获取两个对象中的较大值
template <class T>inline const T& max(const T& a, const T& b)
  • min:获取两个对象中的较小值
template <class T>inline const T& min(const T& a, const T& b)
  • mismatch:平行比较两个序列,返回一对迭代器,分别指出两个序列中的不匹配点
    • 如果全部匹配,分别返回尾后迭代器
    • 第二个序列的长度必须比第一个长,否则结果未可预期。
template <class InputIterator1, class InputIterator2>pair<InputIterator1, InputIterator2> mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2)
  • swap:交换两个对象的内容
template <class T>inline void swap(T& a, T& b)
  • copy:将一个区间的元素拷贝到另一个区间
    • 如果输出区间的末尾与输入区间的起头重叠,可以使用copy
    • 如果输出区间的起头与输入区间的末尾重叠,可能会出现错误。因为copy是一一进行元素的赋值操作,这样会使输入区间的尾部被覆盖。但是copy有时会根据迭代器的特性调用memmove(),它是先将整个输入区间完整复制下来再操作。
    • copy是为输出区间的元素赋予新值,而不是产生新元素,所以不能将元素插入空的迭代器中。
    • 如果指针所指对象拥有trival assignment operator(平凡赋值运算符),可以直接使用内存拷贝(memmove())的方式,而不是逐个赋值的方式
完全泛化版本template <class Inputerator, class OutputIterator>inline OutputInterator copy(InputIterator first, InputIterator last, OutputIterator result)
  • copy_backward:以逆行的方向赋值区间内的每个元素到以result-1为起点的区间上。意思就是把区间复制到result的前面。
    • 迭代器必须是双向迭代器。
    • 如果输出区间尾部与输入区间的头部重合,可能会出现错误。因为输入区间的头部可能已经被覆盖。
    • 其他的特性和copy类似。
template <class BidirectionalIterator1, class BidirectionalIterator2>inline BidirectionIterator2 copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result)
0 0