C++进阶:STL算法18--排列组合算法

1. 简介

函数 作用 文档
next_permutation(beg,end) 取出[beg,end)内的下移一个排列。 next_permutation()
next_permutation(beg,end,comp) 将函数comp代替<操作符,执行next_permutation() next_permutation()
prev_permutation(beg,end) 取出[beg,end)内的上移一个排列。 prev_permutation()
prev_permutation(beg,end,comp) 将函数comp代替<操作符,执行prev_permutation() prev_permutation()

2. 示例代码

  • next_permutation
// next_permutation example
#include      // std::cout
#include     // std::next_permutation, std::sort

int main () {
  int myints[] = {1,2,3};

  std::sort (myints,myints+3);

  std::cout << "The 3! possible permutations with 3 elements:\n";
  do {
    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::next_permutation(myints,myints+3) );

  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}
  • prev_permutation
// next_permutation example
#include      // std::cout
#include     // std::next_permutation, std::sort, std::reverse

int main () {
  int myints[] = {1,2,3};

  std::sort (myints,myints+3);
  std::reverse (myints,myints+3);

  std::cout << "The 3! possible permutations with 3 elements:\n";
  do {
    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::prev_permutation(myints,myints+3) );

  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}

3. 练习

你可能感兴趣的:(C++进阶:STL算法18--排列组合算法)