C ++中的等效LinkedHashmap? [英] equivalent LinkedHashmap in C++?

查看:130
本文介绍了C ++中的等效LinkedHashmap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Java 程序,我想将其转换为 C++.因此,Java 代码中使用了一个 Linkedhashmap 数据结构,我想将其转换为 C++.C++ 中是否有 LinkedHashmap 的等效数据类型?

I have a Java program that I want to convert it to C++. So, there is a Linkedhashmap data structure used in the Java code and I want to convert it to C++. Is there an equivalent datatype for LinkedHashmap in C++?

我尝试使用 std::unordered_map,但是,它不保持插入的顺序.

I tried to use std::unordered_map, however, it does not maintain the order of the insertion.

推荐答案

C++ 不提供具有模仿 Java 的 LinkedHashMap<K,V> 行为的集合模板,因此您需要将顺序与映射分开维护.

C++ does not offer a collection template with the behavior that would mimic Java's LinkedHashMap<K,V>, so you would need to maintain the order separately from the mapping.

这可以通过将数据保存在 std::list> 中,并保存一个单独的 std::unordered_map 映射用于按键快速查找项目:

This can be achieved by keeping the data in a std::list<std::pair<K,V>>, and keeping a separate std::unordered_map<k,std::list::iterator<std::pair<K,V>>> map for quick look-up of the item by key:

  • 在添加项目时,将相应的键/值对添加到列表的末尾,并将键映射到迭代器std::prev(list.end()).立>
  • 通过键删除项目时,查找其迭代器,将其从列表中删除,然后删除映射.
  • 在替换项目时,首先从无序映射中查找列表迭代器,然后将其内容替换为新的键值对.
  • 在迭代值时,只需迭代std::list>.

这篇关于C ++中的等效LinkedHashmap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆