强大的string :: iterator 和next_permutation

本文介绍如何利用C++标准库函数next_permutation来实现字符串或数组的全排列,并通过示例展示了如何控制排列的长度及遍历过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//

NYOJ--STL--擅长排列的小明

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string a="123456789";

int main()
{
int n;
cin >> n;
while(n--)
{
int n,m;
cin >> n >> m;
string output = a.substr(0,m);
cout << output << endl;

string::iterator i=a.begin();
while(next_permutation(i,i+n))
{
if(!(a.substr(0,m) == output ))
{
output = a.substr(0,m);
cout << output << endl;
}
}
}
system("pause");
return 0;
}



函数next_permutation,可以遍历全排列,要包含头文件<algorithm>与之完全相反的函数还有prev_permutation,next函数默认的是从小到大的顺序,pre函数默认的是从大到小的顺序
int main()
{
int a[3];
a[0]=1;a[1]=2;a[2]=3;
do
{
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
} while (next_permutation(a,a+3)); //参数3指的是要进行排列的长度

//如果存在a之后的排列,就返回true。如果a是最后一个排列没有后继,返回false,每执行一次,a就变成它的后继


}

输出:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1


如果改成 while(next_permutation(a,a+2));
则输出:
1 2 3
2 1 3

只对前两个元素进行字典排序
显然,如果改成 while(next_permutation(a,a+1)); 则只输出:1 2 3



若排列本来就是最大的了没有后继,则next_permutation执行后,会对排列进行字典升序排序,相当于循环

int list[3]={3,2,1};
next_permutation(list,list+3);
cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<endl;

//输出: 1 2 3

优化改进以下代码#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <iterator> using namespace std; typedef istream_iterator<string> string_input; void welcome() { cout << "******************* 变位词查找系统*********************\n" << "在词典中找出给定的字符串的所有变位词" << endl; } void readDict(vector<string> & dictionary) { cout << "首先,请输入词典的文件名称:" << endl; string dictionary_name; cin >> dictionary_name; ifstream ifs(dictionary_name.c_str()); if (!ifs.is_open()) { cerr << "异常:文件"<< dictionary_name << "没有找到 " << endl; exit(1); } cout << "词典读入中 ..." << flush; copy(string_input(ifs), string_input(), back_inserter(dictionary)); sort(dictionary.begin(),dictionary.end()); cout << "词典包含有 " << dictionary.size() << " 个单词\n\n"; ifs.close(); } void analyseAnagram(const vector<string> & dictionary) { cout << "请输入单词(或任意字母序列)" << endl; for (string_input p(cin); p != string_input(); ++p) { cout << "查找输入单词的变位词中..." << endl; string word = *p; sort(word.begin(), word.end()); bool found_one = false; do { if (binary_search(dictionary.begin(), dictionary.end(), word)) { cout << " " << word ; found_one = true; } } while (next_permutation(word.begin(), word.end())); if (!found_one) cout << " 抱歉,没有找到变位词\n"; cout << "\n请输入下一个单词 " << "(或输入Ctrl+Z终止程序 ) \n" << endl; } } int main() { welcome(); vector<string> dictionary; readDict(dictionary); analyseAnagram(dictionary); system("pause"); return 0; }
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值