Search code examples
c++c++11stdmapstd-pairstdlist

Using std::map with std::pair as a key and list as value


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)))

Solution

  • 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
        }
    }