请教Accelerated C++的几个习题!
1.以下是Accelerated C++第七章第六题,原程序使用了递归来生成句子,要求改写这个程序,使用两个vector,一个用来保存那个完全展开的句子,另一个用来作为堆栈,而不允许使用任何递归调用。小弟实在是太笨,想不出来如何完成,还请各位大虾多多帮忙!
//begin
#include <string>
#include <map>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cctype>
#include <stdexcept>
using std::string;
using std::map;
using std::istream;
using std::vector;
using std::cout;
using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::logic_error;
using std::domain_error;
using std::find_if;
using std::isspace;
typedef vector<string> Rule;
typedef vector<Rule> Rule_collection;
typedef map<string, Rule_collection> Grammar;
bool space(char c)
{
return isspace(c);
}
bool not_space(char c)
{
return !isspace(c);
}
vector<string> split(const string& s)
{
string::const_iterator i = s.begin(), j;
vector<string> ret;
while ((i = find_if(i, s.end(), not_space)) != s.end()) {
j = find_if(i, s.end(), space);
string t(i, j);
ret.push_back(t);
i = j;
}
return ret;
}
Grammar read_grammar(istream& in)
{
Grammar ret;
string line;
while (getline(in, line)) {
vector<string> entry = split(line);
if (!entry.empty())
ret[entry[0]].push_back(
Rule(entry.begin() + 1, entry.end()));
}
return ret;
}
bool bracketed(const string& s) {
return s.size() > 1 && s[0] == '<' && s[s.size() - 1] == '>';
}
int nrand(int n) {
if (n <= 0 || n > RAND_MAX)
throw domain_error("Argument to nrand is out of range");
const int bucket_size = RAND_MAX / n;
int r;
do r = rand() / bucket_size;
while (r >= n);
return r;
}
void gen_aux(const Grammar& g, const string& word, vector<string>& ret) {
if (!bracketed(word))
ret.push_back(word);
else {
Grammar::const_iterator it = g.find(word);
if (it == g.end())
throw logic_error("empty rule");
const Rule_collection& c = it->second;
const Rule& r = c[nrand(c.size())];
for (Rule::const_iterator i = r.begin(); i != r.end(); ++i)
gen_aux(g, *i, ret);
}
}
vector<string> gen_sentence(const Grammar& g) {
vector<string> ret;
gen_aux(g, "<sentence>", ret);
return ret;
}
int main() {
vector<string> sentence = gen_sentence(read_grammar(cin));
vector<string>::const_iterator it = sentence.begin();
if (!sentence.empty()) {
cout << *it;
++it;
}
while (it != sentence.end()) {
cout << " " << *it;
++it;
}
cout << endl;
return 0;
}
//end
2.还是上面那个程序,其中随机数生成函数nrand,当n>RAND_MAX时,就无法正常工作,现在要求改写那个nrand函数,使得该函数对所有的n都表现良好,这样的难题,小弟更是不知道怎么做了,也请各位大虾多多帮忙了!