#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;
}
Run Code Online (Sandbox Code Playgroud)
运行该代码,请求时输入5个字符串,如:
foo1
foo2
foo3
foo4
foo5
Run Code Online (Sandbox Code Playgroud)
然后你应该能够输入一对数字并输出字符串,就像1 2应该给出foo1但不是.我有什么想法可以解决它吗?
您的代码没有获取数据,因为您输入了1, 2但是地图中没有该对,因为您在for循环中使用的键从零开始,即
0 1
2 3
4 5
6 7
8 9
Run Code Online (Sandbox Code Playgroud)
输入任何这些对应该从地图中给出答案,您已正确实施.