用一对来索引 STL 映射是个好主意吗?

发布于 2024-08-30 03:28:30 字数 158 浏览 5 评论 0 原文

我只是想知道制作一个像“

std::map< std::pair<int,int>,std::string >

只是想知道如何在内部对这些对进行排序”的数据结构是否是一个好主意...:S

谢谢!

I'm just wondering if it is a good idea to make a data structure like

std::map< std::pair<int,int>,std::string >

Just wondering how the pairs would be ordered internally... :S

Thanks!

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

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

发布评论

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

评论(3

晨敛清荷 2024-09-06 03:28:30

这些对将使用对operator<std::map的默认比较操作)进行排序,其中

返回:x.first < y.first || (!(y.first < x.first) && x.second < y.second)

(C++03, 20.2.2/6)

请注意,使用一对可能会造成混淆作为映射键,特别是在使用映射迭代器时(it->first.first 获取键对的第一个元素看起来很荒谬)。但在某些情况下,这可能比为键创建一个全新的结构更容易。

与所有事情一样,请谨慎使用,如果它不简单且易于理解,那么最好找到一种不同的方法来完成它。

The pairs would be ordered using the pair operator< (the default compare operation for std::map), which

Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second)

(C++03, 20.2.2/6)

Note that it could get confusing using a pair as a map key, especially when working with map iterators (it->first.first to get the first element of the key pair just looks ridiculous). But in some cases it might be easier than creating a whole new struct for the key.

As with all things, use with care, and if it's not straightforward and easy to understand, it's probably better to find a different way to do it.

你另情深 2024-09-06 03:28:30

如果您希望哈希表有两个索引,那么您应该查看 Boost::multiindex 容器。

至于回答你的问题,如果你能处理其他人指出的局限性,为什么不呢?我始终支持任何清晰、易于使用且适合当前问题目的的解决方案。

If you're looking to have two indexes for your hash table then you should look at Boost::multiindex containers.

As far as answering your question, why not if you can deal with the limitations others have pointed out. I'm always for any solution that is clear, easy to use, and suits the purposes of the problem at hand.

无法回应 2024-09-06 03:28:30

你可以。在我看来,你应该做一些比这更有表现力的事情,因为 std::pair 并不是为此目的。例如,如果您想通过哈希值将字符串存储在映射中,则可以执行以下操作:

struct Hash {
    int hash_low;
    int hash_high;

    bool operator<(const Hash& other) const;
};

然后使用 map 而不是 map ;,字符串>

You can. In my opinion though you should do something more expressive than that, because std::pair wasn't meant for this. For example, if you want to store strings in a map by their hash then you can do something like:

struct Hash {
    int hash_low;
    int hash_high;

    bool operator<(const Hash& other) const;
};

And then use map<Hash,string> rather than map<pair<int,int>,string>.

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