将元素存储在 unordered_set 中与将它们存储在 unordered_map 中

发布于 2024-12-08 10:52:08 字数 654 浏览 0 评论 0原文

假设我有以下 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 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

两仪 2024-12-15 10:52:08

我会选择 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 with unordered_set I don't have this facility.

As for the mentioned operations, the speed will be almost same.

2024-12-15 10:52:08

由于 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.

打小就很酷 2024-12-15 10:52:08

如果性能是一个重要问题,那么您可能需要分析并查看哪一个性能更好。否则,请选择最符合逻辑地描述您想要做的事情的一项。 [只有 100K 个项目,如果您需要在其他地方订购,我认为 setmap 可能具有可接受的性能]

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 and map may yet have acceptable performance if you need ordering somewhere else]

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