C++新特性unordered_map和tuple

本文介绍了C++中的两种容器——map和unordered_map,以及元组tuple的使用。map是有序且key不重复的容器,基于红黑树实现;unordered_map是无序的,使用哈希表实现。此外,还讲解了元组的构造、元素获取和拆包操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <map>
#include <unordered_map>

#include <tuple>

void test1()
{
    /* map、mutimap都是安装key进行排序的容器,内部实现是红黑树
        插入和搜索的时间复杂度是O(log(size)),区别是map中key不可重复
    */
    std::map<int, std::string> map1 = {
        {1, "1"},
        {3, "3"},
        {2, "2"},
    };

    for (auto &it : map1)
    {
        std::cout << it.first << ":" << it.second << std::endl;
    }
    // 无序map
    std::unordered_map<int, std::string> unmap = {
        {1, "1"},
        {3, "3"},
        {2, "2"},
    };
    for (auto &it : unmap)
    {
        std::cout << it.first << ":" << it.second << std::endl;
    }
}


void test2()
{
    /*元组三要素:除了自定义结构,tuple可以存储不同类型的数据
        1.std::make_tuple:构造元组
        2.std::get<index>/<type>:根据位置或类型获取元组元素
        3.std::tie:元组拆分,缺点需要事先知道元素的个数和对应的具体类型
    */
    std::string nm;
    int age;
    double grade;
    auto tp = std::make_tuple("zhangsan", 10, 99.5);
    // 位置获取元素
    std::cout<<std::get<0>(tp)<<std::endl;
    std::cout<<std::get<1>(tp)<<std::endl;

    // 也可以通过类型获取元素
    std::cout<<std::get<double>(tp)<<std::endl;

    // 元组拆包
    std::tie(nm, age, grade) = std::make_tuple("lisi", 20, 60.5);
    std::cout<<nm<<","<<age<<"," <<grade<<std::endl;

}
int main()
{
    test1();
    test2();
    return 0;
}
unordered_mapC++标准库中的一个关联容器,它提供了一种键值对的映射关系。在unordered_map中,每个键都是唯一的,而值可以重复。通过使用键来访问对应的值,unordered_map可以实现高效的查找操作。 三维索引是指在一个三维空间中,通过三个维度的值来唯一标识一个元素。在使用unordered_map进行三维索引时,可以将三个维度的值组合成一个自定义的结构体或者使用std::tuple作为键,将对应的值作为unordered_map中的值。 下面是一个示例代码,演示了如何使用unordered_map进行三维索引: ```cpp #include <iostream> #include <unordered_map> #include <tuple> struct Index { int x; int y; int z; bool operator==(const Index& other) const { return std::tie(x, y, z) == std::tie(other.x, other.y, other.z); } }; namespace std { template <> struct hash<Index> { size_t operator()(const Index& index) const { return std::hash<int>()(index.x) ^ std::hash<int>()(index.y) ^ std::hash<int>()(index.z); } }; } int main() { std::unordered_map<Index, int> map; // 添加元素 Index index1{1, 2, 3}; map[index1] = 10; // 查找元素 Index index2{1, 2, 3}; if (map.find(index2) != map.end()) { std::cout << "找到了对应的值:" << map[index2] << std::endl; } else { std::cout << "未找到对应的值" << std::endl; } return 0; } ``` 在上面的示例代码中,我们定义了一个名为Index的结构体,用来表示三维索引。为了在unordered_map中使用Index作为键,我们需要重载Index的operator==函数,并在std命名空间中定义一个hash模板特化,用来计算Index的哈希值。 通过使用unordered_map自定义的Index结构体,我们可以实现对三维空间中元素的快速查找访问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值