gather
头文件'boost/algorithm/gather.hpp'有算法gather的两个变体函数。gather() 带了用一对迭代器定义的元素集合,移动里面的元素到序列中的一个合适的位置(枢轴位置)以满足传递进去的谓词。算法移动元素是稳定的。经过算法移动元素后,返回一对迭代器,迭代器指定范围的元素满足谓词的顺序。
API
函数gather返回一对迭代器,此迭代器表示了满足谓词的所有元素。有两个版本的gather变体;一个版本带了一对迭代器,另一个版本带来一个参数范围。
namespace boost { namespace algorithm {
template <typename BidirectionalIterator, typename Pred>
std::pair<BidirectionalIterator,BidirectionalIterator>
gather ( BidirectionalIterator first, BidirectionalIterator last, BidirectionalIterator pivot, Pred pred );
template <typename BidirectionalRange, typename Pred>
std::pair<typename boost::range_iterator<const BidirectionalRange>::type, typename boost::range_iterator<const BidirectionalRange>::type>
gather ( const BidirectionalRange &range, typename boost::range_iterator<const BidirectionalRange>::type pivot, Pred pred );
}}
例如
有如下参数序列arr {0 1 2 3 4 5 6 7 8 9},调用gather( arr, arr + 10, arr + 4, IsEven ) 将返回如下结果
1 3 0 2 4 6 8 5 7 9
|---|-----|
first | second
pivot
上述表示中first second是返回的迭代器。
译者注:根据api可知,传递的参数是arr的整个序列,枢轴量是4,因此,小于4的会直接放置在4的前面,大于4的在后面。又因为上面说了,gather是算法是稳定的,因此0还是在2的前面8还是在6的后面。关于算法的稳定性,可以查看一些排序类的算法说明。
迭代器要求
gather 作用于双向迭代器。这要求来源于gather使用了stable_partition 函数,该函数要求双向迭代器。一些标准的库(比如libstdc++、libc++)已经扩展了stable_partition,这使得使用这些库的函数可以使用前置迭代器。假如在这个情况下,gather也可以作用于前置迭代器上面。
健壮性要求
gather使用了stable_partition,他会尝试去开辟短暂使用的内存,假如内存不可用的话就会不开辟额外的内存,(而是在原有内存中运行函数)。
时间复杂度
假如有足够的内存,那么运行时间是O(N);
假如没有任何可用的内存,运行时间是O(N log N)。