日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

使用STL的next_permutation函数生成全排列(C++)

發布時間:2025/6/15 c/c++ 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用STL的next_permutation函数生成全排列(C++) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

下午研究了一下全排列算法,然后發現C++的STL有一個函數可以方便地生成全排列,這就是next_permutation

在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++程序:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #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; }

其中還用到了 sort 函數和 string.begin()、string.end() ,函數聲明如下:

#include <algorithm>
void sort( iterator start, iterator end );

sort函數可以使用NlogN的復雜度對參數范圍內的數據進行排序。

#include <string>
iterator begin();
const_iterator begin() const;

#include <string>
iterator end();
const_iterator end() const;

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

在使用大數據測試的時候,發現標準C++的效率很差...換成C函數寫一下,效率提升了不止一倍...

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <cstdio> #include <algorithm> #include <cstring> #define MAX 100using namespace 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);}return 0; }

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的使用STL的next_permutation函数生成全排列(C++)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。