我很好奇std::next_permutation
是如何实现的,所以我提取了gnu libstdc++ 4.7
版本并对标识符和格式进行了清理,以生成以下演示...
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
template<typename It>
bool next_permutation(It begin, It end)
{
if (begin == end)
return false;
It i = begin;
++i;
if (i == end)
return false;
i = end;
--i;
while (true)
{
It j = i;
--i;
if (*i < *j)
{
It k = end;
while (!(*i < *--k))
/* pass */;
iter_swap(i, k);
reverse(j, end);
return true;
}
if (i == begin)
{
reverse(begin, end);
return false;
}
}
}
int main()
{
vector<int> v = { 1, 2, 3, 4 };
do
{
for (int i = 0; i < 4; i++)
{
cout << v[i] << " ";
}
cout << endl;
}
while (::next_permutation(v.begin(), v.end()));
}
输出结果如预期:http://ideone.com/4nZdx
我的问题是:它是如何工作的?“i”,“j”和“k”的含义是什么?它们在不同执行部分具有什么值?其正确性证明的草图是什么?显然,在进入主循环之前,它只检查微不足道的0或1个元素列表情况。在进入主循环时,“i”指向最后一个元素(而不是末尾后面的位置),并且列表至少有2个元素。
在主循环的体中发生了什么?
while (true)
语句是一个无限循环,函数只能通过内部return语句来返回循环所包含的内容。 - Andrew Tomazos