简体   繁体   English

将std :: map与std :: pair用作键,并将列表作为值

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

So I have the following map parseTable 所以我有以下地图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. 当我使用地图的find()函数时,我想分别访问列表的每个值。

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

std::map::find will return an iterator to the found element, or to end if not found. std::map::find将迭代器返回找到的元素,或以end ,如果没有找到。 That iterator will point to a std::pair<const Key, Value> , which in your case would translate to 该迭代器将指向std::pair<const Key, Value> ,在您的情况下,它将转换为

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

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. std :: map :: find()返回一个迭代器到找到搜索项的地方,如果找不到,则返回std::map::end() So, in your if statement, you need to check against that: 因此,在您的if语句中,您需要检查以下内容:

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 * find返回一个迭代器,以访问该对象(类型将为std::pair<std::pair<Symbol, Symbol>, list<Symbol>> ,您需要取消引用运算符*

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM