📜  在C ++中实现多维地图

📅  最后修改于: 2021-05-31 21:04:55             🧑  作者: Mango

当我们想将一个值映射到键的组合时,使用多维映射。密钥可以是任何数据类型,包括用户定义的数据类型。多维地图是嵌套地图;也就是说,他们将一个键映射到另一个映射,该映射本身存储键值与对应映射值的组合。

句法:

// Creating a two-dimensional map:
map< key_1_type, map< key_2_type, value_type> > object;

// Creating an N-dimensional map:
map< key_1_type, map< key_2_type, ... map< key_N_type, value_type> > > object;

范例1:

// C++14 code to implement two-dimensional map
  
#include 
using namespace std;
  
int main()
{
  
    // Two-dimensional key
    map > m;
  
    // For accessing outer map
    map >::iterator itr;
  
    // For accessing inner map
    map::iterator ptr;
  
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            m[i][j] = i + j;
        }
    }
  
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
  
            // Accessing through array subscript
            cout << "First key is " << i
                 << " And second key is " << j
                 << " And value is " << m[i][j] << endl;
        }
    }
  
    cout << "\nNow accessing map though iterator \n\n";
  
    for (itr = m.begin(); itr != m.end(); itr++) {
  
        for (ptr = itr->second.begin(); ptr != itr->second.end(); ptr++) {
            cout << "First key is " << itr->first
                 << " And second key is " << ptr->first
                 << " And value is " << ptr->second << endl;
        }
    }
}
输出:
First key is 0 And second key is 0 And value is 0
First key is 0 And second key is 1 And value is 1
First key is 1 And second key is 0 And value is 1
First key is 1 And second key is 1 And value is 2

Now accessing map though iterator 

First key is 0 And second key is 0 And value is 0
First key is 0 And second key is 1 And value is 1
First key is 1 And second key is 0 And value is 1
First key is 1 And second key is 1 And value is 2

范例2:

// C++14 code to implement two-dimensional map
// and inserting value through insert()
  
#include 
using namespace std;
  
int main()
{
  
    // First key type is a string
    map > m;
  
    map >::iterator itr;
    map::iterator ptr;
  
    m.insert(make_pair("Noob", map()));
    m["Noob"].insert(make_pair(0, 5));
  
    m.insert(make_pair("Geek", map()));
    m["Geek"].insert(make_pair(1, 10));
  
    m.insert(make_pair("Geek", map()));
    m["Geek"].insert(make_pair(2, 20));
  
    for (itr = m.begin(); itr != m.end(); itr++) {
  
        for (ptr = itr->second.begin(); ptr != itr->second.end(); ptr++) {
            cout << "First key is " << itr->first
                 << " And second key is " << ptr->first
                 << " And value is " << ptr->second << endl;
        }
    }
}
输出:
First key is Geek And second key is 1 And value is 10
First key is Geek And second key is 2 And value is 20
First key is Noob And second key is 0 And value is 5
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”