So i am reading accelerated c++ and have reached the 7th chapter which is introducing me to maps. In the last example of the chapter the author uses
maps to generate random sentences.
I have read the code and the explanation numerous times but can still not understand how you can push back words into a vector of vectors much less how the final Grammar map is supposed to look like after we give it the input.
Can anyone tell me how to push back into multidimensional vector and/or how the map will look like after the execution of this function
"<noun> cat
<noun> dog
<noun> table
<noun-phrase> <noun>
<noun-phrase> <adj ective> <noun-phrase>
<adj ective> large
<adj ective> brown
<adj ective> absurd
<verb> j umps
<verb> sits
<location> on the stairs
<location> under the sky
<location> wherever it wants
<sentence> the <noun-phrase> <verb> <location>"
typedef vector<string> Rule;
typedef vector<Rule> Rule_collection;
typedef map<string, Rule_collection> Grammar;
// read a grammar from a given input stream
Grammar read_grammar(istream& in)
{
Grammar ret;
string line;
// read the input
while (getline(in, line)) {
// `split' the input into words
vector<string> entry = split(line);
if (!entry.empty())
// use the category to store the associated rule
ret[entry[0]].push_back(
Rule(entry.begin() + 1, entry.end()));
}
return ret;
}
Each of the different <categories> will have a vector of Rules, assuming split splits on spaces.
So accessing ret["<verb>"] would be the Rules {{"jumps"}, {"sits"}}
Then what is the point of using a vector of vector if the map just looks like:
First(string) Second(vector)
verb jumps sits
And how would the entry be stored for sentence or noun phrase?
Well each rule is an individual in a grammar. The vectors of vectors are to be interpreted as vectors of Rules. That is most likely why the author is using the typedefs.
ret["<noun-phrase>"] would be the Rules {{"<noun>"}, {"<adjective>", "<noun-phrase>"}}
Did you know much about language grammars before reading this book? Language grammars can be quite a complex topic.
Thank you very much!
After rereading the code a couple of times and looking at your responses with the sample output i now understand the code and what is happening :D