c++ - unordered_map 值对 C++

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

我正在尝试在 C++ 中使用 unordered_map,这样,对于键,我有一个 int,而对于值,有一对 float 。但是,我不确定如何访问这对值。我只是想弄清楚这个数据结构。我知道要访问元素,我们需要一个与此无序映射声明类型相同的 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

感谢您的帮助和时间。

最佳答案

是的,这是正确的,但是不要使用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;
}

关于c++ - unordered_map 值对 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29821668/

相关文章:

c++ - 使用 std::less 创建一个 std::map 环绕原点

c++ - 使用 boost 序列化、std::tr1::unordered_map 和自定义键的奇怪行为

c++ - 不区分大小写 unordered_map<string, int>

c++ - 在Qt5应用程序上读取CSV文件时出现无限循环

c++ - 为什么 GetProcessImageFileName 返回 null 而不是进程的地址?

C++ 类 vector 推回错误

c++ - volatile 是通知编译器并发访问变量的正确方法吗

c++ - 在 C++ 中嵌套的 unordered_maps

c++ - 将成员函数指针转换为具有多个参数的标准 C 函数

c++ - QML - 如何将变量从一个 qml 文件发送/传递到另一个 qml 文件