c++ - 查找一张 map 是否是另一张 map 的子集

标签 c++ map

我有两个 STL map 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 的子集。

由于元素在 map 中排序,我认为 从 foo 中的 bar 开始寻找第一个元素,然后寻找连续的元素 来自该位置的 foo 中的 bar。

这里的问题是我无法找到在 cpp 中使用 STL 映射的方法。 对于从 map 中的某个位置到 map 末尾的每个发现,我能否缩小 map 中的搜索范围?

我希望我解释了问题。

最佳答案

使用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;
           });
}

关于c++ - 查找一张 map 是否是另一张 map 的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16045108/

相关文章:

c++ - 在 IFileSaveDialog 中使用 GetEditBoxText

c++ - 禁用 Windows 中的文件夹虚拟化

c++ - 使用 MPI_Send 和 MPI_Recv 从所有处理器发送到根。

c++ - std::set 和 std::map 有什么区别

c++ - 使用结构作为 STL 映射键的要求?

scala - Scala 中的 'yield' 是否等同于 map 函数?

c++ - 使用 getline 函数获取段错误?

c++ - 使用英特尔 TBB 的低效斐波那契数列比非线程实现慢得多

c++ - 在映射中使用对作为键 (C++/STL)

c++ - std::map<key_type, value_type>::find(different_key_type)