简体   繁体   中英

How do I get a set intersection of two std::unordered_map's?

I have two std::unordered_map instances with 0 or more intersecting keys. I am trying return a new instance of std::unordered_map whose keys are the intersection of the keys of mapA and mapB and whose values at those keys are from mapA .

How can I find the set intersection of these two maps mapA and mapB while keeping only the values from mapA ?

The following provides an example of the results I am trying to achieve:

#include <unordered_map>

typedef std::unordered_map<std::string, double> MapType;

MapType intersectFilter(MapType const & mapA, MapType const & mapB);

int main()
{
    MapType mapA = { {"keyA",  1}, {"keyB", 2} };
    MapType mapB = { {"keyA",  5}, {"keyK", 3} };

    MapType mapC = intersectFilter(mapA, mapB);
    // The resulting `mapC` should be:
    // { {"keyA", 1} }

    return 0;
}

The most straightforward implementation is:

MapType intersectFilter(const MapType& mapA, const MapType& mapFilter)
{
    MapType result;
    for (const auto& pair: mapA)
    {
        if (mapFilter.find(pair.first) != mapFilter.end())
            result.insert(pair);
    }

    return result;
}

I've changed type of parameters to const references, since probably you don't want to copy the parameters.

You aren't removing entries, you are conditionally copying. That sounds like a job for std::copy_if .

MapType intersectFilter(MapType const & mapA, MapType const & mapFilter)
{
    MapType result;
    auto inserter = std::inserter(result, result.end());
    auto predicate = [&mapFilter](MapType::const_reference item) 
    { return mapFilter.find(item.first) == mapFilter.end(); }; // or mapFilter.contains in C++20
    std::copy_if(mapA.begin(), mapA.end(), inserter, predicate);
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM