将元素存储在 unordered_set 中与将它们存储在 unordered_map 中
假设我有以下 User 结构:
struct User {
string userId;
UserType userType; // UserType is just an enumeration
string hostName;
string ipAddress;
//and more other attributes will be added here
};
并且我需要存储用户记录的集合(大约 10^5 个用户,也可以扩展到更高)。如果我将其存储为 unordered_set 或 unordered_map 性能会更好吗? Unordered_set 在技术上与 HashSet 相同,unordered_map 与 HashMap 相同,对吗?使用常规集(有序)不是一个选择,因为当元素数量增加时插入和删除会变得非常慢。
unordered_set <User> userRecords;
或者
unordered_map <string, User> userRecords; // string is the user ID.
我需要它在插入、删除以及通过其 userId 访问特定用户对象方面非常快。
Suppose I have the following User struct:
struct User {
string userId;
UserType userType; // UserType is just an enumeration
string hostName;
string ipAddress;
//and more other attributes will be added here
};
and I need to store a collection of user records (around 10^5 users, can scale higher too ). Would it be better in performance if I store it as an unordered_set or unordered_map? Unordered_set is technically the same as HashSet, and unordered_map is the same as HashMap, right? Using a regular set (ordered) is not an option, as insertion and deletion will get very slow when the number of elements increase.
unordered_set <User> userRecords;
OR
unordered_map <string, User> userRecords; // string is the user ID.
I need it to be very fast in terms of insertion, deletion, and to access a particular user object by its userId.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会选择
unordered_map
,因为我可以随时给定用户 ID 来获取用户,而无需任何额外的工作,而使用unordered_set
我没有此功能。至于上述操作,速度几乎是一样的。
I would choose
unordered_map
, because I can get a user, given a userid at any time, without any extra work, while withunordered_set
I don't have this facility.As for the mentioned operations, the speed will be almost same.
由于
unordered_set<>
无法让您通过 userId 轻松访问用户,因此unordered_map<>
似乎是正确的选择。Since the
unordered_set<>
doesn't give you the possibility to easily access a user by his userId,unordered_map<>
seems to be the correct choice.如果性能是一个重要问题,那么您可能需要分析并查看哪一个性能更好。否则,请选择最符合逻辑地描述您想要做的事情的一项。 [只有 100K 个项目,如果您需要在其他地方订购,我认为
set
和map
可能具有可接受的性能]If performance is a significant concern then you'll probably want to profile and see which one performs better. Otherwise, choose the one that most logically describes what you're trying to do. [With only 100K items I think
set
andmap
may yet have acceptable performance if you need ordering somewhere else]