Question

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

Running that code, put in 5 strings when it asks, like:

foo1
foo2
foo3
foo4
foo5

Then you should be able to enter a pair of numbers and get the string out, like 1 2 should give foo1 but it doesn't. Any ideas how I can fix it?

Was it helpful?

Solution

Your code does not get the data because you entered 1, 2 but the map does not have that pair in it, because the keys that you used in the for loop start at zero, i.e.

0 1
2 3
4 5
6 7
8 9

Entering any of these pairs should give you an answer from the map, which you have implemented correctly.

Demo on ideone.

OTHER TIPS

It's a good idea for you to learn how to diagnose problems. You could have identified your problem by yourself by printing the contents of the map.

#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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top