【问题标题】:unordered_map pair of values c++unordered_map 值对 c++
【发布时间】:2015-07-01 12:48:35
【问题描述】:

我正在尝试在 C++ 中使用unordered_map,这样,对于键我有一个int,而对于值有一对浮点数。但是,我不确定如何访问这对值。我只是想理解这个数据结构。我知道要访问我们需要与此无序映射声明类型相同的iterator 的元素。我尝试使用iterator->second.firstiterator->second.second。这是访问元素的正确方法吗?

typedef std::pair<float, float> Wkij;
tr1::unordered_map<int, Wkij> sWeight;
tr1::unordered_map<int, Wkij>:: iterator it;
it->second.first     //  access the first element of the pair
it->second.second    //  access the second element of the pair

感谢您的帮助和时间。

【问题讨论】:

  • unordered_map 是 C++11 标准的一部分,您可以使用 std:: 代替 tr1::
  • 你也可以使用std::get&lt;0&gt;(it-&gt;second)std::get&lt;0&gt;(std::get&lt;1&gt;(*it))(两者都给出it-&gt;second.first,这是完全有效的)
  • 感谢您的建议。

标签: c++ c++11 unordered-map std-pair keyvaluepair


【解决方案1】:

是的,这是正确的,但不要使用tr1,写std,因为unordered_map 已经是STL 的一部分。

像你说的那样使用迭代器

for(auto it = sWeight.begin(); it != sWeight.end(); ++it) {
    std::cout << it->first << ": "
              << it->second.first << ", "
              << it->second.second << std::endl;
}

在 C++11 中也可以使用基于范围的 for 循环

for(auto& e : sWeight) {
    std::cout << e.first << ": "
              << e.second.first << ", "
              << e.second.second << std::endl;
}

如果你需要它,你可以像这样使用std::pair

for(auto it = sWeight.begin(); it != sWeight.end(); ++it) {
    auto& p = it->second;
    std::cout << it->first << ": "
              << p.first << ", "
              << p.second << std::endl;
}

【讨论】:

  • 谢谢你,@NikolayKondratyev。很有帮助!
猜你喜欢
  • 2015-05-24
  • 2021-01-22
  • 2011-05-29
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
相关资源
最近更新 更多