# next_permutation和pre_permutation源码解析

9 篇文章 0 订阅

### 1.next_permutation

template <class BidirectionalIterator>
bool next_permutation(BidirectionalIterator first,
BidirectionalIterator last) {
if (first == last) return false; //空数组
BidirectionalIterator i = first;
++i;
if (i == last) return false; //只有一个元素
i = last;
--i;

for(;;) {
BidirectionalIterator ii = i;
--i;
if (*i < *ii) { //查找一对相邻的元素，且*i < *ii
BidirectionalIterator j = last;
while (!(*i < *--j)); //从最尾端开始，查找第一个大于*i的数
iter_swap(i, j); //交换*j和*i
reverse(ii, last); //将迭代器[first, last]范围内的数据颠倒
return true;
}
if (i == first) { //进行到最前面
reverse(first, last); //重新开始排
return false;
}
}
}

template <class BidirectionalIterator>
inline void reverse(BidirectionalIterator first, BidirectionalIterator last) {
__reverse(first, last, iterator_category(first));
}
template <class RandomAccessIterator>
void __reverse(RandomAccessIterator first, RandomAccessIterator last,
random_access_iterator_tag) {
while (first < last) iter_swap(first++, --last); //将迭代器[first, last]范围内的数据颠倒
}

### 2.pre_permutation

template <class BidirectionalIterator>
bool prev_permutation(BidirectionalIterator first,
BidirectionalIterator last) {
if (first == last) return false; //空数组
BidirectionalIterator i = first;
++i;
if (i == last) return false; //只有一个元素
i = last;
--i;

for(;;) {
BidirectionalIterator ii = i;
--i;
if (*ii < *i) { //查找一组相邻的元素，且*i > *ii
BidirectionalIterator j = last;
while (!(*--j < *i)); //从最尾端开始，查找第一个小于*i的数
iter_swap(i, j); //交换
reverse(ii, last); //将迭代器[first, last]范围内的数据颠倒
return true;
}
if (i == first) { //进行到最前面
reverse(first, last); //从头开始排
return false;
}
}
}
template <class BidirectionalIterator>
inline void reverse(BidirectionalIterator first, BidirectionalIterator last) {
__reverse(first, last, iterator_category(first));
}
template <class RandomAccessIterator>
void __reverse(RandomAccessIterator first, RandomAccessIterator last,
random_access_iterator_tag) {
while (first < last) iter_swap(first++, --last); //将迭代器[first, last]范围内的数据颠倒
}


### 3.具体运用

https://leetcode.com/problems/next-greater-element-iii/

1.《STL库源码解析》------侯捷

2.《STL3.0》源码

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
01-31 168
02-26 633
03-22 651
07-23 1857
12-02 526
03-28 1300
04-25 213
04-07 144
05-20 1109
08-01 844

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。