【问题标题】:Using std::map with std::pair as a key and list as value使用 std::map 和 std::pair 作为键和列表作为值
【发布时间】:2018-05-16 07:07:25
【问题描述】:

所以我有下面的地图parseTable

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

如果我以这种方式初始化我的地图,我对如何访问列表值感到困惑:

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

当我使用地图的find() 函数时,我想单独访问列表中的每个值。

这是我想出的,但我无法获得对该索引值的引用:

 if (parseTable.find(std::pair(stack_symbol.top(), current_symbol)))

【问题讨论】:

  • 为什么是 map 而不是 unordered_map?
  • 如果您不需要对列表中的值进行排序,多映射可能会更好。

标签: c++ c++11 stdmap std-pair stdlist


【解决方案1】:

std::map::find 将返回一个迭代器到找到的元素,如果没有找到则返回到end。该迭代器将指向std::pair&lt;const Key, Value&gt;,在您的情况下将转换为

std::pair&lt; const std::pair&lt;Symbol, Symbol&gt;, list&lt;Symbol&gt; &gt;

你想要的是这样的

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

【讨论】:

  • std::pair&lt;const Key, Value&gt;.
  • 所以std::pair&lt;const std::pair&lt;Symbol, Symbol&gt;, list&lt;Symbol&gt; &gt;
【解决方案2】:

这不是地图键的最佳选择,它不会让地图得到有效使用。

std::map::find() 将迭代器返回到找到搜索项的位置,如果没有找到则返回std::map::end()。所以,在你的 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 返回一个迭代器,用于访问对象(类型为std::pair&lt;std::pair&lt;Symbol, Symbol&gt;, list&lt;Symbol&gt;&gt;,您需要取消引用运算符*

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多