在 C++ 中,std::map 是一个非常有用的容器,它存储的元素是一对键值对,并且这些键值对是根据键来排序的。std::map 的键和值可以是任何类型,但是键类型必须能够进行比较,因为 std::map 内部是通过比较键来排序和查找元素的。
多类型键值对
如果你想在 std::map 中使用多类型作为键或值,你可以使用 std::pair、std::tuple 或者自定义结构体作为键。
#include
#include
int main() {
std::map<std::pair<int, char>, std::string> myMap;
myMap[{1, ‘a’}] = “Hello”;
myMap[{2, ‘b’}] = “World”;
for (const auto& pair : myMap) {
std::cout << pair.first.first << ", " << pair.first.second << ": " << pair.second << std::endl;
}
return 0;
}
#include
#include
int main() {
std::map<std::tuple<int, char, double>, std::string> myMap;
myMap[{1, ‘a’, 3.14}] = “Pi”;
myMap[{2, ‘b’, 2.71}] = “e”;
for (const auto& pair : myMap) {
std::cout << std::get<0>(pair.first) << ", " << std::get<1>(pair.first) << ", " << std::get<2>(pair.first) << ": " << pair.second << std::endl;
}
return 0;
}
#include
#include
struct MyKey {
int id;
char code;
bool operator<(const MyKey& other) const {
if (id != other.id) {
return id < other.id;
}
return code < other.code;
}
};
int main() {
std::map<MyKey, std::string> myMap;
myMap[{1, ‘a’}] = “First”;
myMap[{2, ‘b’}] = “Second”;
for (const auto& pair : myMap) {
std::cout << pair.first.id << ", " << pair.first.code << ": " << pair.second << std::endl;
}
return 0;
}