next_permutation()实现全排序

#include <string>  
#include <algorithm>  
#include <iostream>  
 
void func(const char *str_in) 

    std::string str(str_in);  
    std::sort(str.begin(),str.end());  
    std::cout<<str<<std::endl;
    do  
    { 
        std::cout<<str<<std::endl; 
    }while (std::next_permutation(str.begin(),str.end())); 

 
int main(int argc, char* argv[]) 

    func("cba"); 
    return 0; 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
next_permutation函数是C++ STL提供的一个函数,用于求一个序列的下一个字典序排列。它可以通过包含头文件<algorithm>来使用。使用方法如下: ```cpp #include <algorithm> using namespace std; int main() { int a\[\] = {1, 2, 3}; do { // 处理当前排列 } while (next_permutation(a, a + 3)); return 0; } ``` 如果想手动实现next_permutation函数,可以使用以下方法: ```cpp bool next_permutation(int* a, int n) { int i = n - 2; while (i >= 0 && a\[i\] >= a\[i + 1\]) { i--; } if (i < 0) { return false; } int j = n - 1; while (j >= 0 && a\[i\] >= a\[j\]) { j--; } swap(a\[i\], a\[j\]); reverse(a + i + 1, a + n); return true; } ``` 如果排列本来就是最大的,没有后继,那么在调用next_permutation函数后,会对排列进行字典升序排序,相当于循环。例如: ```cpp int list\[3\] = {3, 2, 1}; next_permutation(list, list + 3); cout << list\[0\] << " " << list\[1\] << " " << list\[2\] << endl; ``` 输出结果为 "1 2 3"。 #### 引用[.reference_title] - *1* *2* [C++中 next_permutation 函数的使用方法、原理及手动实现](https://blog.csdn.net/m0_51913750/article/details/130540032)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [next_permutation函数简要](https://blog.csdn.net/weixin_53518090/article/details/113345164)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值