您需要提供反向映射。有很多方法可以做到这一点,包括multimap
,但是如果您的映射在创建之后未被修改就是遍历映射并构建反向映射,那么这是一种简单的方法。在反向映射中,映射值 - >键列表。
下面的代码使用std::unordered_map
来将std::pair<int, int>
(原始地图中的值)映射到std::vector<int>
(原始地图中的按键列表)。反向映射的该建筑是简单和简洁:
std::unordered_map<Point, std::vector<int>, hash> r;
for (const auto& item : m) {
r[item.second].push_back(item.first);
}
(见的hash
定义中的完整的例子)。
有没有必要担心密钥是否存在;当您尝试使用r[key]
表示法访问该密钥时,它将被创建(并且该ID的向量将被初始化为空向量)。
该解决方案针对简单性;如果您需要这样做并且不关心性能,内存使用情况或使用Boost等第三方库,那么这是一个可行的解决方案。
如果您在意这些事情,或者您在进行双向查找的同时修改地图,则应该探索其他选项。
Live example
#include <iostream>
#include <map>
#include <unordered_map>
#include <vector>
// Define a point type. Use pair<int, int> for simplicity.
using Point = std::pair<int, int>;
// Define a hash function for our point type:
struct hash {
std::size_t operator()(const Point& p) const
{
std::size_t h1 = std::hash<int>{}(p.first);
std::size_t h2 = std::hash<int>{}(p.second);
return h1^(h2 << 1);
}
};
int main() {
// The original forward mapping:
std::map<int, Point> m = {
{1, {2, 3}},
{5, {6, 2}},
{12, {2, 3}},
{54, {4, 4}},
{92, {6, 2}}
};
// Build reverse mapping:
std::unordered_map<Point, std::vector<int>, hash> r;
for (const auto& item : m) {
r[item.second].push_back(item.first);
}
// DEMO: Show all indices for {6, 2}:
Point val1 = {6, 2};
for (const auto& id : r[val1]) {
std::cout << id << " ";
}
std::cout << "\n";
// DEMO: Show all indices for {2, 3}:
Point val2 = {2, 3};
for (const auto& id : r[val2]) {
std::cout << id << " ";
}
std::cout << "\n";
}
提供一些你的代码,请 – Sugar