c++ - 两个 `std::map` 的交集

标签 c++ dictionary std stdmap c++-standard-library

鉴于我有两个 std::map,比如说:

map<int, double> A;
map<int, double> B;

我想得到两张 map 的交集,形式如下:

map<int, pair<double,double> > C;

其中键是 both AB 中的值,值是 A< 中的一对值B 分别。 有没有使用标准库的干净方法?

最佳答案

#include <map>
#include <utility>
template <typename KeyType, typename LeftValue, typename RightValue>
std::map<KeyType, std::pair<LeftValue, RightValue>>
IntersectMaps(const std::map<KeyType, LeftValue>& left, 
              const std::map<KeyType, RightValue>& right) {
    std::map<KeyType, std::pair<LeftValue, RightValue>> result;
    typename std::map<KeyType, LeftValue>::const_iterator il  = left.begin();
    typename std::map<KeyType, RightValue>::const_iterator ir = right.begin();
    while (il != left.end() && ir != right.end()) {
        if (il->first < ir->first)
            ++il;
        else if (ir->first < il->first)
            ++ir;
        else {
            result.insert(std::make_pair(il->first, std::make_pair(il->second, ir->second)));
            ++il;
            ++ir;
        }
    }
    return result;
}

我还没有测试过,甚至没有编译过……但它应该是 O(n)。因为它是模板化的,所以它应该适用于任何两个共享相同键类型的 map 。

关于c++ - 两个 `std::map` 的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3772664/

相关文章:

c++ - 优先队列 : Using an object to compare instead of a class

c++ - std::string 中的堆损坏?

python - 如何合并列表中的损坏文本并附加到字典中?

python - 检查字典键是否存在并处理其值的最有效方法

python - MySQL fetchall() - 如何在字典中而不是在元组中获取数据

c++ - 为什么 std::sort() 会改变排序后的 vector ?

c++ - 当命名的 lambda 用作模板类参数或构造函数参数时,类模板无法编译

c++ - 如何使用CMake自动链接Boost库

c++ - boost::transform 与 std::transform

c++ - C++11 STL 中的容器