您需要提供反向映射。有很多方法可以做到這一點,包括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