#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 中得到答案,您已正确实现。
关于c++ - 如何拥有带有两个键的 map ? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23546813/