c++ - 如何拥有带有两个键的 map ? C++

标签 c++ dictionary std-pair

#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {

    std::map<std::pair<int, int>, std::string> mymap;
    for(int i = 0; i < 10; i = i + 2) {
        std::pair<int, int> temp;
        temp.first = i;
        temp.second = i+1;
        std::string temp2;
        std::cout << "Enter a string: ";
        std::cin >> temp2;
        mymap[temp] = temp2;
    }

    while(1) {
        int temp, temp2;
        std::cout << "Enter a number: ";
        std::cin >> temp;
        std::cout << "Enter another number: ";
        std::cin >> temp2;

        std::pair<int, int> test;
        test.first = temp;
        test.second = temp2;
        std::cout << mymap[test] << std::endl;
    }

    return 0;
}

运行该代码,在它询问时输入 5 个字符串,例如:

foo1
foo2
foo3
foo4
foo5

然后你应该能够输入一对数字并得到字符串,比如 1 2 应该给出 foo1 但它没有。有什么办法可以解决吗?

最佳答案

您的代码未获取数据,因为您输入了 1, 2 但 map 中没有该对,因为您在 for 中使用的键循环从零开始,即

0 1
2 3
4 5
6 7
8 9

输入这些对中的任何一个都应该从 map 中得到答案,您已正确实现。

Demo on ideone .

关于c++ - 如何拥有带有两个键的 map ? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23546813/

相关文章:

c++ - 为什么这两种访问部分 C++ 映射对的方式不同

c++ - 有效检查包装在 `std::pair` s 中的对象集合的属性

c++ - "extra qualification"错误。标准如何保证?

c++ - 在不实例化模板的情况下访问模板类的公共(public)静态成员?

c++ - 需要使上下文可用于 C++ ostream 插入运算符

excel - VBA : Error 457 : this key is already associated with an element of collection 中的嵌套字典

c++ - 使用声明来表示模板声明中的类型

c# - 保持字典的 Where() 一致

python - 在 python 中创建互惠字典

c++ - 为什么我需要在 map::emplace 中为不可复制对象的单个 arg 构造函数使用分段构造?