html - Fencepost issue: I need a recursive function that skips executing a section when it is first called -
html - Fencepost issue: I need a recursive function that skips executing a section when it is first called -
i'm trying create c++ programme creates formatted css file.
what first take html file , build tree nodes of next type.
struct node { std::string element_type; std::vector<std::string> class_list; std::string iden; std::vector<node*> children; };
right i'm trying create function takes root of tree , returns string formatted css of document (with attributes it's looking @ beingness css class
es , id
s).
for example, if html file
<html> <body> <div class="row"> <h1 id="title">here's title</h1> </div> <div class="row red"> <p>here's text within div of class row , red</p> </div> <div class="row"> <a href="google.com">cool, can click here go google</a> </row> </body> </html>
then, after had been made tree, have function
std::string doctree::_tree2str(node * rt)
which intend have homecoming string
html {} html > body {} html > body > div.row {} html > body > div.row > h1#title {} html > body > div.row > {} html > body > div.row.red {} html > body > div.row.red > p {}
here's implementation of function:
std::string doctree::_tree2str(node * rt) { std::string css(""); if (rt) { css.append(rt->element_type); if (!rt->class_list.empty()) { (std::vector<std::string>::iterator it(rt->class_list.begin()), offend(rt->class_list.end()); != offend; ++it) { css.append("." + *it); } } if (!rt->iden.empty()) { css.append("#" + rt->iden); } if (!rt->children.empty()) { (std::vector<node*>::iterator it(rt->children.begin()), offend(rt->children.end()); != offend; ++it) { css.append("\n\t" + _tree2str(*it)); } } } homecoming css; }
the thing i've skipped " > "
because don't how work recursive function. should printed @ origin of function every time function called except first time.
also, there might other logical fallacies. can help me out here?
you can create private _innertree2str(node * rt, bool printgt)
method contains contents of _tree2str
method, plus line if(printgt) css.append(" > ");
@ top. calls _tree2str(node)
become calls _innertree2str(node, true)
then _tree2str
becomes
std::string doctree::_tree2str(node * rt) { homecoming _innertree2str(rt, false); }
this way first time phone call _innertree2str
printgt
variable false , won't append " > "
, every other time printgt
true
rather creating sec method instead add together printgt
parameter straight _tree2str
, you'll relying on caller remember pass in false
printgt
parameter
html c++ css algorithm recursion
Comments
Post a Comment