设为首页 加入收藏

TOP

用STL的函数生成全排列
2013-07-23 09:07:08 来源: 作者: 【 】 浏览:221
Tags:STL 函数 成全 排列

  使用STL的next_permutation函数生成全排列

  在C++(www.cppentry.com) Reference中查看了一下next_permutation的函数声明:

  #include

  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++(www.cppentry.com)程序:

123456789101112131415161718
#include <iostream>#include <algorithm>#include <string> usingnamespace 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;}return0;}

  其中还用到了 sort 函数和 string.begin()、string.end() ,函数声明如下:

  #include

  void sort( iterator start, iterator end );

  sort函数可以使用NlogN的复杂度对参数范围内的数据进行排序。

  #include

  iterator begin();

  const_iterator begin() const;

  #include

  iterator end();

  const_iterator end() const;

  string.begin()和string.end() 可以快速访问到字符串的首字符和尾字符。

  在使用大数据测试的时候,发现标准C++(www.cppentry.com)的效率很差...换成C函数写一下,效率提升了不止一倍...

123456789101112131415161718192021
#include <cstdio>#include <algorithm>#include <cstring>#define MAX 100 usingnamespace std; int main(){int length;char str[MAX];gets(str);    length =strlen(str);    sort(str, str + length);puts(str);while(next_permutation(str, str + length)){puts(str);}return0;}

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇AC自动机简单题 下一篇运用递归的方法求等比数列

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: