如何拥有两个键的地图? C ++

时间:2014-05-08 15:59:01

标签: c++ map 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,但事实并非如此。我有什么想法可以解决它吗?

2 个答案:

答案 0 :(得分:5)

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

0 1
2 3
4 5
6 7
8 9

输入这些对中的任何一对都应该从地图中给出答案,您已正确实施。

Demo on ideone

答案 1 :(得分:2)

了解如何诊断问题是个好主意。您可以通过打印地图内容自行确定问题。

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

    std::map<std::pair<int, int>, std::string>::iterator iter = mymap.begin();
    for ( ; iter != mymap.end(); ++iter )
    {
      std::cout
       << "Key: (" << iter->first.first << ", " << iter->first.second << "), Value: "
       << iter->second << std::endl;
    }

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