STL算法如何识别它正在操作的容器类型?
例如,sort
接受迭代器作为参数。
它怎么知道要对哪种容器进行排序呢?
STL算法如何识别它正在操作的容器类型?
例如,sort
接受迭代器作为参数。
它怎么知道要对哪种容器进行排序呢?
它并不需要 :-) 这就是迭代器的全部意义——对它们进行操作的算法不需要知道底层容器的任何信息,反之亦然。
那么它是如何工作的呢?嗯,迭代器本身具有一定的众所周知的属性。例如,'随机访问'迭代器允许任何算法通过一个常量访问偏移量与迭代器相对应的元素:
std::vector<int> vec = { 1, 2, 3, 4 };
assert(*(vec.begin() + 2) == 3);
为了进行排序,迭代器需要支持随机访问(以任意顺序访问第一个和最后一个迭代器之间的所有元素),并且它们需要是可写的(以便分配或交换值),也被称为“输出”迭代器。
输出迭代器与输入(只读)迭代器的示例:
std::vector<int> vec = { 1, 2, 3, 4 };
*vec.begin() = 9;
assert(vec[0] == 9);
*vec.cbegin() = 10; // Does not compile -- cbegin() yields a const iterator
// that is 'random-access', but not 'output'
std::swap()
可以交换两个任意的东西(它是为通用情况而模板化的,并针对某些类型进行了专门优化以提高速度)。std::vector::swap
仅将一个向量的内容与另一个向量的内容交换。 - Cameronstd::vector::swap
,而已经有了 std::swap
?它提供了什么优势? - cppcoderstd::vector::swap
存在于单独的位置,但是将交换实现作为向量实现的一部分确实是有意义的。对于向量,std::swap
只是调用std::vector::swap
:-) - Cameron它不需要知道容器的类型,只需要知道迭代器的类型。
template<class IteratorType,
class IntegerDiffType> inline
void advance(IteratorType& it, IntegerDiffType n)
对于双向迭代器,它需要多次应用 ++ 或 --;对于随机访问迭代器,它可以一次跳跃。此函数用于 std::binary_search、std::lower_bound 和其他一些算法。
在内部,它使用迭代器类型特征来选择策略:
template<class IteratorType,
class IntegerDiffType>
void advance(IteratorType& it, IntegerDiffType n)
{
typedef typename iterator_traits<IteratorType>::category category;
advance_impl(it, n, category());
}
template<class IteratorType,
class IntegerDiffType>
void advance(IteratorType& it, IntegerDiffType n, bidirectional_iterator_tag)
{ // increment iterator by offset, bidirectional iterators
for (; 0 < n; --n)
++it;
for (; n < 0; ++n)
--it;
}
template<class IteratorType,
class IntegerDiffType>
void advance(IteratorType& it, IntegerDiffType n, random_access_iterator_tag)
{ // increment iterator by offset, random-access iterators
it += n;
}