系列文章
此系列总结常用STL函数
1、全排列函数
STL提供了两个用来计算排列组合关系的算法,分别是next_permutation和prev_permutation。依其字面意思,next_permutation是当前排列的“下一个”排列组合;prev_permutation是当前排列的“上一个”排列组合。所谓“上一个”、“下一个”的顺序是依照当前排列顺序的字典序。
1)next_permutation
示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[]={1,2,3};
while(next_permutation(a,a+3)){
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
}
return 0;
}
运行结果:
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
通过观察运行结果可知,next_permutation按照字典序将除当前序列的其他排列序列全部输出。若想要输出全部排列序列,即在当前例子下也将1 2 3输出,需要将代码改为:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[]={1,2,3};
do{
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
}while(next_permutation(a,a+3));
return 0;
}
运行结果:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
2)prev_permutation
示例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[]={2,1,3};
do{
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
}while(prev_permutation(a,a+3));
return 0;
}
运行结果:
2 1 3
1 3 2
1 2 3
2、substr
定义
substr()是C++语言函数,主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。如果没有指定长度_Count或_Count+_Off超出了源字符串的长度,则子字符串将延续到源字符串的结尾。
形式
str.substr(pos, len)
示例:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str="abcdefg";
string a,b,c;
//默认的 pos 为0,len 为 str.size()
a=str.substr();
//从指定位置开始(下标为2)指定长度(长度为3)的string
b=str.substr(2,3);
//若长度超出,则只复制到原string的末尾
c=str.substr(4,20);
cout<<"(下标提示)"<<endl;
cout<<"0123456"<<endl;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
return 0;
}
运行结果:
(下标提示)
0123456
abcdefg
cde
efg
3、fill
对一个容器的值进行填充时,我们就可以使用fill()或fill_n()函数。
示例:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
vector<int> v(10);//容器的长度为5
fill(v.begin(),v.end(),8);//将容器全部填充为8
int n=v.size();
for(int i=0;i<n;i++){
cout<<v[i]<<" ";
}
cout<<endl;
fill(v.begin()+1,v.end()-1,5);//指定位置填充
for(int i=0;i<n;i++){
cout<<v[i]<<" ";
}
cout<<endl;
fill_n(v.begin()+3,3,6);
for(int i=0;i<n;i++){
cout<<v[i]<<" ";
}
return 0;
}
运行结果:
8 8 8 8 8 8 8 8 8 8
8 5 5 5 5 5 5 5 5 8
8 5 5 6 6 6 5 5 5 8
4、__gcd
求两个数的最大公约数。
#include<bits/stdc++.h>
using namespace std;
int main(){
int a=24,b=12;
int ans=__gcd(a,b);
cout<<ans;
return 0;
}
运行结果:
12
本文介绍了C++标准模板库(STL)中的一些实用函数,包括next_permutation和prev_permutation用于生成排列组合,substr用于复制子字符串,fill及fill_n用于容器填充,以及__gcd用于计算最大公约数。
428

被折叠的 条评论
为什么被折叠?



