在嵌套的 STL 映射中插入和迭代

inserting and iterating in nested STL map

本文关键字:插入 迭代 映射 嵌套 STL      更新时间:2023-10-16

修改:使代码更具可读性

我最近发布了一个关于嵌套 STL 映射的问题,但我没有输入任何代码,所以我再次问同样的问题(这次包含代码(。任何帮助将不胜感激,并对垃圾邮件表示歉意。

在过去的 4 天里,我被困在某件事上,现在我需要指导。

以下是我的数据结构:

class demo1
{
    int a, b, c, d, e;
}
class demo2
{
    map(int, demo1) map1
}
map(string, demo2) map2;
vector< pair<int, demo1> > vec1;
现在,假设我有 2 个字符串变量(在 map2 的"键"中

(和 3 个 int 变量(在 map1 的"键"中(,如何在 map2 和 map1 之间建立正确的映射

这是我期望的输出:

// Expected mapping output
string 1(key in map2)
int 1(key in map1) -> demo1
int2               -> demo1
int 3              -> demo1
string 2
int 1(key in map1) -> demo1
int2               -> demo1
int 3              -> demo1

这是代码的相关部分(上面描述的数据结构在头文件中,这是我使用它们的主要.cpp文件。实际代码很长,我只插入其中的相关部分(

class tmp1
{
    int a, b, c, d e;
} t1;
....
if(condition is true)
{
    string tmp_string // this string is a key in map2
    map2.insert(make_pair(tmp_string, demo2));
}
if(another condition is true)
{
    int n; // this is a "key" in map1
    demo 1 d1 // create an instance of class demo1
    d1.a =  t1.a;
    d1.b =  t1.b;
    d1.c =   t1.c;
    d1. d =   t1.e;
    d1.f  = t1.f;
    // Insert these value into map now
    map1.insert(make_pair(n, d1));
    vec1.push_back(make_pair(n, d1));  // vec1 is define above in the data structure section
}

这是我检查输出的方式

map(string, demo2)::iterator outer_itr;
map(int, demo1)::iterator inner_itr;
for(outer_itr = map2.begin(); outer_itr != map2.end(); outer_itr++)
{
    cout << "String is " << (*outer_itr).first << endl;
    vector < pair<int, demo1> >::iterator itr;
    for(itr = vec1.begin(); itr != vec1.end(); itr++)
    {
        cout << "Int key in map1 is " << (*itr).first           << endl;
        cout << "Value of a is      " << (*itr).second.second.a << endl;
        cout << "Value of b is      " << (*itr).second.second.b << endl;
        cout << "Value of c is      " << (*itr).second.second.c << endl;
    }
}

这是进行映射的正确方法吗..?

阅读后,我认为您的代码只是使用 demo2 作为地图,正如@Leeor所述,您正在用 vec1 复制地图功能,但这实际上也发生在demo2 中。因此,您的最终解决方案应消除vec1demo2

有两种

方法可以实现此目的:

如果您希望能够直接索引到demo1中,那么在您的代码中您将执行map2["string 1"].map1[1]那么您需要合并您的键

  • 所以你的容器看起来像这样:std::map< std::pair< std::string, int >, demo1 > map2
  • 索引如下所示: map2[std::make_pair("string 1", 1(]

如果您希望能够遍历附加到"字符串 1"的所有值,那么您的代码在 for 块中似乎正在做什么,那么您需要使用 multimap

  • 所以你的容器看起来像这样: std::multimap< std::string, std::pair< int, demo1 > > map2
  • 插入将如下所示:map2.insert( std::make_pair( 1, myDemo1 )
  • 你会得到一个迭代器的std::pairfirst是开始迭代器,second是结束迭代器,如下所示:auto itr = map2.equal_range( "string 1" )

如果您需要上述两个功能,则需要嵌套映射,如@jrok