IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    STL中的next_permutation函数生成全排列

    admin发表于 2016-02-26 10:02:36
    love 0

    在C++ Reference中查看了一下next_permutation的函数声明:

    #include <algorithm>
    bool next_permutation( iterator start, iterator end );

    The next_permutation() function attempts to transform the given range of elements [start,end) into the next lexicographically greater permutation of elements. If it succeeds, it returns true, otherwise, it returns false.

    从说明中可以看到 next_permutation 的返回值是布尔类型。按照提示写了一个标准C++程序:

    #include <iostream>
    #include <algorithm>
    #include <string>
     
    using namespace std;
     
    int main()
    {
        string str;
        cin >> str;
        sort(str.begin(), str.end());
        cout << str << endl;
        while (next_permutation(str.begin(), str.end()))
        {
            cout << str << endl;
        }
        return 0;
    }
    
    // next_permutation example
    #include <iostream>     // std::cout
    #include <algorithm>    // 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;
    }

    参考:cplusplus手册,使用STL的next_permutation函数生成全排列(C++)



沪ICP备19023445号-2号
友情链接