C++抽象编程——递归策略(3)——生成排列数(2)

来源:互联网 发布:mysql front 5.3 注册 编辑:程序博客网 时间:2024/06/10 14:48

课本的原本代码

上次我们讲完了生成排列数的原理C++抽象编程——递归简介(3)——生成排列数(1),那么我们接下来就是实现它了。在这篇的前一篇我特意去提了一下foreach语句,就是因为这个文章涉及到。那么我们先看看书上的代码:

#include <iostream>#include "set.h"#include "simpio.h"using namespace std;/* Function prototypes */Set<string> generatePermutations(string str);/* Main program */int main() {    string str = getLine("Enter a string: ");    cout << "The permutations of \"" << str << "\" are:" << endl;    foreach (string s in generatePermutations(str)) {        cout << " \"" << s << "\"" << endl;    }    return 0;}Set<string> generatePermutations(string str) {    Set<string> result;    if (str == "") {    result += "";    } else {        for (int i = 0; i < str.length(); i++) {    char ch = str[i];    string rest = str.substr(0, i) + str.substr(i + 1);    foreach (string s in generatePermutations(rest)) {        result += ch + s;    }   } }    return result;}

我以前说过,这书上的代码我们直接复制粘贴是用不了的,因为这里包含了太多他们学校自己的库函数,比如 “simpio.h”,再比如

Set<string> result;result += "";

在STL的set中也是没有这样的运算符的。那我们拿出来有什么用呢?
1. 我为了验证上一篇的foreach语句 C++抽象编程——递归策略(3)——foreach语句的简单实现
2. 这样能更好的理解我是怎么改写为我们用标准的C++库就能实现的程序。

上面的代码如果运行正确,那就是这样的结果:

改写程序

下面我们就用上一篇文章C++抽象编程——递归策略(3)——foreach语句的简单实现中提到的方法来改写foreach语句,并且利用我们标准库的函数来完成这个程序,让我们看起来更加熟悉。分析我就不写了,代码的注释很详细:

#include <iostream>#include <set>#include <string> using namespace std;/*函数原型*/ set<string> generatePermutations(string str); /*主函数*/ int main(){    string line,elementOfPermutations;    set<string> permutations;//将所得的排列数储存在这里     set<string>::iterator it;    cout << "Enter a string ";     getline(cin, line);    cout << "The permutations of \"" << line << "\" are:" << endl;    /*下面的步骤相当于 foreach语句*/     permutations = generatePermutations(line);    for (it = permutations.begin(); it != permutations.end(); it++){        elementOfPermutations = (*it); //将元素从容器中逐个提取出来         cout << " \"" << elementOfPermutations << "\"" << endl;//输出     }    return 0;}/*返回的类型是 set<string>类,所以可以调用方法*/ set<string> generatePermutations(string str) {    set<string> result;    set<string> permutations;    set<string>:: iterator it;    string elementOfPermutations;    if (str == "") {        result.insert("");    } else {  //递归调用     for (int i = 0; i < str.length(); i++) {    char ch = str[i];//决定开头的元素    /*截取除了该元素的其他元素,并重组为一个新的字符串*/     string rest = str.substr(0, i) + str.substr(i + 1);    /*在剩下的元素中调用生成排列数的函数,并存入permutations中*/     permutations = generatePermutations(rest);    /*遍历产生的排列数,然后在其前面补上开头元素,装到result中,以便返回*/     for(it = permutations.begin(); it != permutations.end(); it++){        elementOfPermutations = (*it);        result.insert(ch + elementOfPermutations);        }      }    }    return result;}

PS:写代码的时候,感觉命名确实很重要,当时为了好调试,我随便起了名字,但是总是搞乱。后来起了标准的英文,这样就好多了。
我们看看运行结果吧:

0 0
原创粉丝点击