在嵌套的 STL 映射中插入和迭代
inserting and iterating in nested STL map
修改:使代码更具可读性
我最近发布了一个关于嵌套 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
中。因此,您的最终解决方案应消除vec1
和demo2
。
方法可以实现此目的:
如果您希望能够直接索引到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::pair
,first
是开始迭代器,second
是结束迭代器,如下所示:auto itr = map2.equal_range( "string 1" )
如果您需要上述两个功能,则需要嵌套映射,如@jrok
相关文章:
- 列表的有效性在插入后开始迭代器
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++ 向量插入和迭代器混淆
- 在插入容器之前转换输出迭代器
- 如何将元素插入和迭代到这种映射.C++
- 插入 boost::multi_index 后迭代器变得无效?
- unordered_set范围插入与迭代器
- 如果迭代器没有因插入而无效,则使用std::find和C::insert()是线程安全的
- 使用条件迭代器插入到向量中
- 向量<pointer>:插入(迭代器,指针)插入垃圾值
- 并行STL插入迭代器,例如std :: back_insert_iterator
- unordered_map在结束迭代器上插入
- 重新插入元素可以"re-validate"迭代器吗?
- C 无法在列表上的迭代后使用插入物来附加值
- 在 std::vector 中插入迭代器范围
- 如何普遍有效地填充缓冲液?(传递插入迭代器?器皿?等)
- 在范围 (C++) 之外列出插入迭代器
- 插入迭代器与容器的成员函数插入器
- C++列表在范围外插入迭代器
- 映射插入迭代器绑定