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

时间:2013-04-16 19:08:31

标签: 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酒吧。

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

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

3 个答案:

答案 0 :(得分: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;
           });
}

答案 1 :(得分:3)

您可以提取两个地图(set1set2)的关键字集(foobar),只要它们已排序,您就可以执行以下内容:

if (std::includes(set1.begin(), set1.end(),
                  set2.begin(), set2.end())) {
  // ...
}

请参阅std::includes

答案 2 :(得分:2)

一种简单的方法是将Boost.Rangeboost::includes结合使用:

using namespace boost::adaptors;
bool result = includes(foo | map_keys, bar | map_keys);

以下是最小的完整程序的外观(映射值被忽略):

#include <map>
#include <iostream>
#include <boost/range.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>

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}};

    using namespace boost::adaptors;
    std::cout << includes(foo | map_keys, bar | map_keys);
}

这是live example

相关问题