next_permutation

函数模板

std::next_permutation                               <algorithm>


default (1)
template <class BidirectionalIterator>
  bool next_permutation (BidirectionalIterator first,
                         BidirectionalIterator last)
custom (2)
template <class BidirectionalIterator, class Compare>
  bool next_permutation (BidirectionalIterator first,
                         BidirectionalIterator last, Compare comp);

 

 

 

 

 

将当前序列转换为下一个排列

将序列range[first,last)重排,变为下一个字母序更大的排列。

一个排列(permutation)是指元素可能发生的N!中的每一个(N表示序列中元素的总个数)。不同的排列,可以依据彼此间字母序的比较来重排;第一个按字母序排列的可能数列(first permutation)(这个数列相较于其他所有数列,字母序最小)是所有元素按升序排列所组成的数列,而字母序最大的序列(largest)由所有元素按降序组成。

每个独立元素间的比较,在第一个版本中使用操作符<,在第二个版本中使用函数comp。

如果这个函数可以决定下一个更高的排列,它会按这种比较方式重排序列并返回true. 如果它不能(因为已经是最大可能的序列了),它会将序列重排位第一序列(first permutation)(将数据按升序排列整理)并且返回false.

 

Parameter(参数)


 first,last

       指向序列初始和最终位置的双向迭代器(Bidirectional iterators). 这个序列所使用的的是[first,last),这包含        了first和last间所有的元素,包括被first指向的元素,不包括被first指向的元素。

comp

       接受由双向迭代器(BidirectionalIterator)所指向的类型的两个参数的二进制函数,返回一个可以转换为            bool类型的值。返回的参数表明,第一个参数,是否能以函数所定义的严格小的方式,置于第二个参数前面。

 

Return Value(返回值)


 如果函数能按字母序更大的方式重排当前序列,返回true。

否则,函数返回false,表明现在的排列并不比之前的排列字母序大,相反可能更低。

 

Example(举例)


 

 1 // next_permutation example
 2 #include <iostream>     // std::cout
 3 #include <algorithm>    // std::next_permutation, std::sort
 4 
 5 int main () {
 6   int myints[] = {1,2,3};
 7 
 8   std::sort (myints,myints+3);
 9 
10   std::cout << "The 3! possible permutations with 3 elements:\n";
11   do {
12     std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
13   } while ( std::next_permutation(myints,myints+3) );
14 
15   std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
16 
17   return 0;
18 }

 

输出:

The 3! possible permutations with 3 elements:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
After loop: 1 2 3

复杂度


 first与half一半距离的线性相关

 

 

原文地址:https://www.cnblogs.com/zhenghao2/p/6512992.html