c++ map 多类型

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值