本文主要是介绍算法库-全排列,递归全排列 auti()字符转为整型 stringstream用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
导航
1.全排列函数next_permutation(beg,end)
2.auti() //将字符串转化为整型
万能头文件 #include < bits/stdc++.h>
3.stringstream的int型转为string型用法
——————————————————————————————————— 1.全排列:可以推举出所有可能性
头文件:#include < algorithm>
例1:(int型)
#include <iostream>
using namespace std;
#include <algorithm>
int main()
{int a[] = {1,3,2}; //如果数组中数不是升序的话sort(a,a+len); //注意要排一下序int len = sizeof(a)/sizeof(a[0]); //计算出数组中数量 do{for(int i=0;i<len;i++){cout<<a[i];}cout<<endl;}while(next_permutation(a,a+len)); //这个函数返回的是bool类型,没有更多排列返回false return 0;
}
运行结果:
例2:(string型)
#include <iostream>
using namespace std;
#include <algorithm>
#include <string>
int main()
{string s;cin>>s;do{cout<<s<<endl;}while(next_permutation(s.begin(),s.end())); return 0;
}
运行结果:
例3:(vector容器)
#include <iostream>
using namespace std;
#include <algorithm>
#include <vector>
int main()
{vector<int> v;for(int i=0;i<=2;i++){v.push_back(i);}do{for(vector<int>::iterator it=v.begin();it!=v.end();it++) //迭代器遍历{cout<<*it;}cout<<endl;}while(next_permutation(v.begin(),v.end())); //放入迭代器return 0;
}
运行结果:
手动写一个递归全排列:
学习网址:https://www.bilibili.com/video/av65164273?from=search&seid=12828774151800623150
使用for循环:
#include <stdio.h>
int main()
{int a,b,c;for(a=1;a<=3;a++)for(b=1;b<=3;b++)for(c=1;c<=3;c++)if(a!=b&&a!=c&&b!=c)printf("%d%d%d\n",a,b,c);return 0;
}
运行结果:
———————————————————————————————————
2.atoi() //将字符串转化为整型
要保证atoi中是char*型
c语言:
#include <stdio.h>
#include <stdlib.h> //要加头文件
int main()
{char *s = "123"; //放到atoi中要char*型 int a = atoi(s);printf("%d",a); //输出123return 0;
}
c++:
#include <iostream>
using namespace std;
#include <stdlib.h>
int main()
{string s = "123";int a = atoi(s.c_str()); //中间要转换为char*型cout<<a<<endl;return 0;
}
———————————————————————————————————
3.stringstream的int型转为string型用法
#include <iostream>
#include <sstream> //要添加头文件
using namespace std;
int main()
{int a = 145;string b;stringstream ss; //定义 ss<<a;//传入 ss>>b;//转成string型 if(b == "145"){cout<<"相同类型"<<endl; } else{cout<<"不同类型"<<endl;}return 0;
}
这篇关于算法库-全排列,递归全排列 auti()字符转为整型 stringstream用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!