Sag*_*gar 2 c++ unordered-map set-intersection
我有两个 std::unordered_map
std::unordered_map<int, int> mp1;
std::unordered_map<int, int> mp2;
Run Code Online (Sandbox Code Playgroud)
我需要找到键值对的交集并将其存储在表单的另一个映射中。
std::unordered_map<int, int> mp;
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点??
您可以使用std::set_intersection填充包含两个映射中存在的key,value对的新容器。set_intersection需要的范围进行排序(这正是你不会从获得unordered_map),所以要么,更换unordered_map为smap或创建临时mapS(或临时std::set<std::pair<int, int>>使用前S) set_intersection。
如果您经常需要交叉点,我建议您将原始unordered_maps替换为有序maps 以提高效率:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <unordered_map>
#include <vector>
int main() {
std::map<int, int> mp1 {{1,0}, {2,0}, {3,0}};
std::map<int, int> mp2 {{0,0}, {2,0}, {3,0}};
// this can be unordered unless you plan to use it in an intersection later:
std::unordered_map<int, int> mp;
std::set_intersection(
mp1.begin(), mp1.end(),
mp2.begin(), mp2.end(),
std::inserter(mp, mp.begin())
);
for(auto[key, val] : mp) {
std::cout << key << ',' << val << '\n';
}
}
Run Code Online (Sandbox Code Playgroud)
可能的输出:
3,0
2,0
Run Code Online (Sandbox Code Playgroud)
如果你想留在unordered_maps 而不必创建临时sets 或maps,你可以set_intersection用手动填充器替换上面的:
const auto& [min, max] = std::minmax(mp1, mp2,
[](auto& a, auto& b) {
return a.size() < b.size();
});
for(auto& [key, value] : min) { // iterate over the smallest map
auto fi = max.find(key); // find in the bigger map
if(fi != max.end() && fi->second == value)
mp.emplace(key, value); // add the pair if you got a hit
}
Run Code Online (Sandbox Code Playgroud)
迭代最小映射的原因是为了将find操作次数降到最低。考虑一个地图包含 1 个元素和其他 1000000 个元素的情况。然后您需要 1 次查找而不是 1000000。
一个更通用的解决方案可能是用它制作一个函数模板:
template<
class Key,
class T,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator< std::pair<const Key, T> >
>
auto unordered_map_intersection(
const std::unordered_map<Key,T,Hash,KeyEqual,Allocator>& mp1,
const std::unordered_map<Key,T,Hash,KeyEqual,Allocator>& mp2)
{
std::unordered_map<Key,T,Hash,KeyEqual,Allocator> mp;
const auto& [min, max] = std::minmax(mp1, mp2,
[](auto& a, auto& b) {
return a.size() < b.size();
});
for(auto& [key, value] : min) { // iterate over the smallest map
auto fi = max.find(key); // find in the bigger map
if(fi != max.end() && fi->second == value)
mp.emplace(key, value); // add the pair if you got a hit
}
return mp;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
318 次 |
| 最近记录: |