2

So I have the following map parseTable

std::map<std::pair<Symbol, Symbol>, list<Symbol> > parseTable; 

I am confused on how to access to the list value if I have my map initialized this way:

std::map<std::pair<Symbol, Symbol>, list<Symbol> > parseTable = { 
        {{Symbol::Input, Symbol::OpenPar}, {Symbol::Expr, Symbol::Semicolon, Symbol::InputP}},
        {{Symbol::Input, Symbol::Ident}, {Symbol::Expr, Symbol::Semicolon, Symbol::InputP}},
        {{Symbol::Input, Symbol::Number}, {Symbol::Expr, Symbol::Semicolon, Symbol::InputP}}
};

I want to access to each of the values of my list individually when I use the find() function of my map.

This is what I have come up with but I am not able to get a reference to that index value:

 if (parseTable.find(std::pair(stack_symbol.top(), current_symbol)))
2
  • Why map and not unordered_map? Commented May 16, 2018 at 7:24
  • If you do not need the values in the list to be ordered, a multimap might be better. Commented May 16, 2018 at 7:51

2 Answers 2

4

std::map::find will return an iterator to the found element, or to end if not found. That iterator will point to a std::pair<const Key, Value>, which in your case would translate to

std::pair< const std::pair<Symbol, Symbol>, list<Symbol> >

What you want is something like this

auto it = parseTable.find(std::pair(stack_symbol.top(), current_symbol));

if (it != parseTable.end()) { // A match was found
    //it->first is std::pair<Symbol, Symbol>
    //it->second is list<Symbol>
    for (auto& symbol : it->second) {
        //symbol is each individual value in the list
        ... do something with symbol
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

std::pair<const Key, Value>.
so std::pair<const std::pair<Symbol, Symbol>, list<Symbol> >
2

This is not the greatest choice for map key, it won't let the map to be used efficiently.

std::map::find() return an iterator to the place where it found searched item or std::map::end() if not found. So, in your if statement, you need to check against that:

std::map<std::pair<Symbol, Symbol>, list<Symbol> >::iterator iter =
     parseTable.find(std::pair(stack_symbol.top(), current_symbol)) //or auto with C++11
if (iter != parseTable.end())

find returns an iterator, to access the object (which will be of type std::pair<std::pair<Symbol, Symbol>, list<Symbol>>, you'll need dereference operator *

Symbol currentSymbol = (*iter).first.second; //dummy example to show the use
std::list<Symbol> myList = (*iter).second'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.