STL和string类
STL和string类
string类虽然不是STL的组成部分,但设计它时考虑到了STL,例如,它包含begin()、end()、rbegin()和rend()等成员,因此可以使用STL接口。
例:显示一个词的字母得到所有的排列组合。排列组合就是重新安排容器中元素的顺序。next_permutation()
算法将区间内容转换为下一种排列顺序方式。按照字母递增的顺序进行。成功返回true,区间处于最后的序列中,则返回false。要得到区间内容的所有排列组合,应从最初的顺序开始,应此使用了sort()。
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string letters;
cout<<"Enter the letter grouping (quit to quit):";
while(cin>>letters && letters !="quit")
{
cout<<"Permutations of"<<letters<<endl;
sort(letters.begin(),letters.end());
cout<<letters<<endl;
while(next_permutation(letters.begin(),letters.end()))
cout<<letters<<endl;
cout<<"Enter next sequence (quit to quit):";
}
cout<<"Done.\n";
return 0;
}
注:next_permutation()自动提供唯一的排列组合,这就是输出中"awl“排列组合比“all”的排列组合多。
版权声明:本文为weixin_50866517原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。