请教Accelerated C++的几个习题!

ZenInPalm 2004-08-03 11:12:17
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都表现良好,这样的难题,小弟更是不知道怎么做了,也请各位大虾多多帮忙了!
...全文
116 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
kaphoon 2004-08-06
  • 打赏
  • 举报
回复
1.递归改成非递归,通常就把它改为用栈来实现~
你那个程序太长了,你自己找本数据结构的书看看吧

2.RAND_MAX=32767
你可以用两个随机数相加就ok拉,但是如果你产生一个int,必须要在int的范围内~

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧