I am reading a Data Structures and Algorithms book and there is a case study on recursion, specifically a parser that uses recursive descent. I'm a bit new to C++ (I'm learning it on the side and as I go with Stanley B. Lippman's C++ Primer 5th edition).
I'm a bit stuck on code and am trying to make sense of it. Is what I've written at the bottom (bulleted points) accurate descriptions of what is happening in the functions? I would post the header, but it's a bit too long, you can probably find it online if you search "Data Structures and Algorithms in C++ by Adam Drozdek - interpreter.h".
double Statement::findValue(char* id) {
IdNode tmp(id);
list<IdNode>::iterator i = find(idList.begin(), idList.end(), tmp);
if (i != idList.end())
return i->value;
else
issueError("Unknown variable");
return 0;
}
void Statement::processNode(char* id, double e) {
IdNode tmp(id, e);
list<IdNode>::iterator i = find(idList.begin(), idList.end(), tmp);
if (i != idList.end())
i->value = e;
else
idList.push_front(tmp);
}
findValue()
processNode()
Define a function that accepts a pointer to char (likely it's an array) and returns a double
:
double Statement::findValue(char* id) {
Create a temporary (will die at 'return') of type IdNode
based on that pointer:
IdNode tmp(id);
Use a (std::
I guess, but it could be any function with the same features) function that looks for tmp
inside the container idList
. The result is an interator i
, which must be of the same type of that one used by the container:
list<IdNode>::iterator i = find(idList.begin(), idList.end(), tmp);
Check if something is found. idList.end()
means "one past end", beyond the last item in the container:
if (i != idList.end())
Return the member value
(which is part of IdNode
) for the item found. If value
is not a double
then convert to it.
return i->value;
Otherwise, call issueError
function.
else
issueError("Unknown variable");
Exit function, returning a double
with value = 0:
return 0;
}
Same, but: this function accepts two parameters and returns nothing:
void Statement::processNode(char* id, double e) {
Same, but: IdNode
constructor uses two parameters:
IdNode tmp(id, e);
Same
list<IdNode>::iterator i = find(idList.begin(), idList.end(), tmp);
Same
if (i != idList.end())
Now, modify the item found. Just update value
member:
i->value = e;
Otherwise, add tmp
, insert it at the very begining of idList
container.
else
idList.push_front(tmp);
Exit function:
}