我有两个 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/