如何在三维数组中使用std::map来存储/检索具有特定值的键

How to use std::map in three dimensional array for storing/retrieving key with specific value

本文关键字:检索 存储 map 数组 三维 std      更新时间:2023-10-16

你能告诉我们如何使用std:map作为三维数组吗?我想像mymap[I][j][k]一样访问各个元素,以检查它是否存在,如果存在,它包含什么值,以及它是否与我的期望值匹配。如果它与我的期望值匹配,那么从映射中删除条目(键,值)。这就是我如何创建三维数组和迭代器-

std::map<int, map<int, map<int, unsigned long long int> > > MyMap;
std::map<int, map<int, map<int, unsigned long long int> > >::iterator it;
if (I==0 && j==4 && k==0) MyMap[i][j][k]= MemAddress.unlonglong(); //store a value to key 
//Now I want to check if key exists where i=0,j=4,k=0 and if it is having "0x1234567" as expected value. If key value matches with my expected value then delete the key-value entry from MyMap and print whole table (MyMap) at the end. 

有多种方法可以做到这一点。您可以使用自定义结构作为密钥,如@Krom建议的,如下所示:

struct Key { int a, b, c; };
(...)
std::map<Key, unsigned long long int> MyMap;

您也可以使用元组:

std::map<std::tuple<int, int, int>, unsigned long long int> MyMap;

或者成对使用(我认为你不应该这样做,因为它不干净)

std::map<std::pair<int, std::pair<int, int>>, unsigned long long int> MyMap;

仅仅使用结构可能是最干净的选择。使用该结构,您可以通过以下方式访问它(遵循示例代码):

if (I==0 && j==4 && k==0) MyMap[{i, j, k}]= MemAddress.unlonglong();

要插入新元素,您也可以使用:

MyMap.insert(std::make_pair<Key, unsigned long long int>({i, j, k}, MemAddress.unlonglong());