map 和 unordered_map

发布于 2023-09-13 10:21:49 字数 2456 浏览 38 评论 0

对比

operationmapunordered_map
Orderingincreasing order (by default)No ordering
ImplementationSelf balancing BST (RBT)Hash Table
search timelog(n)O(1) -> Average O(N)-> Worst Case
Insertion timelog(n) + RebalanceSame as search
Deletion timelog(n) + RebalanceSame as search

Use std::map when

  • You need ordered data.
  • You would have to print/access the data (in sorted order).
  • You need predecessor/successor of elements.
  • See advantages of BST over Hash Table for more cases.

Use std::unordered_map when

  • You need to keep count of some data (Example – strings) and no ordering is required.
  • You need single element access i.e. no traversal.

unordered_set && set

  • unordered_set 类似 于 unordered_map No ordering Hash Table
  • set: RBT

Code

std::map<int, std::string> ismap;
isunordered[100] = "test000";
isunordered[10] = "test001";
isunordered[110] = "test002";
isunordered[9] = "test003";
isunordered[1100] = "test004";
isunordered[107] = "test005";
ismap[100] = "test000";
ismap[10] = "test001";
ismap[110] = "test002";
ismap[9] = "test003";
ismap[1100] = "test004";
ismap[107] = "test005";
std::cout << "unordered :" << std::endl;
for (auto x : isunordered)
{
	std::cout << x.first << " : " << x.second.c_str() << std::endl;
}
std::cout << "map :" << std::endl;
for (auto x : ismap)
{
	std::cout << x.first << " : " << x.second.c_str() << std::endl;
}

Result :

unordered :
100 : test000
10 : test001
110 : test002
9 : test003
1100 : test004
107 : test005
map :
9 : test003
10 : test001
100 : test000
107 : test005
110 : test002
1100 : test004

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

乄_柒ぐ汐

暂无简介

文章
评论
28 人气
更多

推荐作者

李珊平

文章 0 评论 0

Quxin

文章 0 评论 0

范无咎

文章 0 评论 0

github_ZOJ2N8YxBm

文章 0 评论 0

若言

文章 0 评论 0

南…巷孤猫

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文