查找一个地图是否是另一个地图的子集

sau*_*abh 7 c++ map

我有两个STL地图std::map<int, int> foo = {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};和std::map<int, int> bar = {{2, 0}, {4, 0}, {5, 0}};

我想找到bar是否是foo的子集.

由于元素是按照地图排序的,我想在foo中找到bar中的第一个元素,然后从该位置找到foo中bar的连续元素.

这里的问题是我无法找到一种方法来使用cpp中的STL映射.我可以减少地图中从地图中的某个位置到地图末尾的每个查找的搜索范围吗?

我希望我解释了这个问题.

jro*_*rok 9

将std::includes算法与仅比较键的自定义比较器一起使用:

#include <map>
#include <algorithm>
#include <iostream>

int main()
{
    std::map<int, int> foo = {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};
    std::map<int, int> bar = {{2, 0}, {4, 0}, {5, 0}};
    typedef std::pair<int,int> pair;

    std::cout <<
       std::includes(foo.begin(), foo.end(), bar.begin(), bar.end(),
           [](const pair& p1, const pair& p2)
           {
               return p1.first < p2.first;
           });
}
Run Code Online (Sandbox Code Playgroud)