如何在C++中创建元组的unordered_map

如何在C++中创建元组的unordered_map

元组 – 元组是一个可以容纳多个元素的对象。元素可以是不同的数据类型。元组的元素是按将要访问的顺序作为参数初始化的。

unordered_map不包含用于元组的哈希函数。因此,如果我们想要哈希元组,则必须显式为其提供可以哈希元组的哈希函数。

unordered_map最多可以使用5个参数:

  • Key :键值的类型。
  • Value :要存储在键下的值的类型。
  • Hash Function :用于哈希给定键的函数。如果未提供,则使用默认哈希函数。
  • Pred :用于确保没有两个键具有相同哈希值的函数。
  • Alloc :用于为映射定义内存模型的对象。

hash_function可以是任何格式,只要它可以哈希给定键。

语法:

unordered_map<tuple<数据类型,数据类型,数据类型>,数据类型,哈希函数> map_of_tuple;

// CPP程序演示unordered_map的实现
//用于元组。
  
#include <bits/stdc++.h>
using namespace std;
  
//用于散列元组的哈希函数
struct hash_tuple {
  
    template <class T1, class T2, class T3>
  
    size_t operator()(
        const tuple<T1,T2,T3>& x)
        const
    {
        return get<0>(x) ^ get<1>(x) ^ get<2>(x);
    }
};
  
int main()
{
  
    //发送哈希函数
    //作为第三个参数
    unordered_map<tuple<int,int,int>,
                  bool,hash_tuple>
        mapOfTuple;
  
    //创建要用作键的一些元组
    tuple<int,int,int> t1(100,200,300);
    tuple<int,int,int> t2(400,500,600);
    tuple<int,int,int> t3(700,800,900);
  
    //在unordered_map中插入值
    mapOfTuple [t1] = true;
    mapOfTuple [t2] = false;
    mapOfTuple[t3] = true;
  
    cout <<“unordered_map的内容:\n”;
    for(auto p:mapOfTuple)
        cout <<“[”<< get<0>(p.first) << “,”
             << get<1>(p.first) << “,”
             << get<2>(p.first)
             << “] ==>”<< p.second << “\n”;
  
    return 0;
}  

输出

unordered_map的内容:
[700,800,900] ==> 1
[100,200,300] ==> 1
[400,500,600] ==> 0

注意: 不需要在自平衡BST映射中传递哈希函数。换句话说,map<tuple<数据类型,数据类型,数据类型>,数据类型> mp可以正常工作。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程