在 C++ 中交换映射的键和值
我正在寻找 C++ 中的一个函数来交换地图的内容...... 那是: 那些曾经是钥匙的现在变成了物品,那些曾经是物品的现在变成了钥匙。 你能告诉我是否有这方面的事情吗?
I'm looking for a function in C++ that for swap the contents of a map ...
that is:
those that were the keys now become the items and those that the items were now the keys.
Can you tell me if there is something about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Geoffroy 所说,std::map 不允许这种行为。但是,您可能想要使用类似 STL 的容器 Boost.Bimap - 双向地图。
As Geoffroy said,
std::map
doesn't allow this behaviour. However, you might want to use a STL-like container Boost.Bimap - bidirectorial map.没有标准的方法/方式可以做到这一点,您必须编写自己的函数。
这并不是什么很难做的事情,但首先要考虑以不同的方式来做。
如果您必须反转您的键/值,那么您的代码可能有问题,但您没有保留容器的逻辑。
如果您需要更多信息,请解释为什么要这样做。
There's no standard method / way to do this, you have to write your own function.
It's not something very hard to do, but first think about doing it in a different way.
If you have to invert your key/values, then you're code may be ill-though, you don't keep the logic of the container.
If you want more information, explain why you want to do this.
将映射中的项目插入多重映射 - 首先是值,其次是键,并使用适当的比较函数来比较原始映射的两个值。插入所有值键项后,多重映射将按预期排序。工作完成了!
Insert the items in the map into a multimap - value first, key second, with appropriate comparison function that compares two values of the original map. Once all value-key items are inserted, the multimap will be sorted as intended. Job done!