查找一个地图是否是另一个地图的子集 [英] Find if one map is subset of another
问题描述
我有两个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}};
I have two STL maps std::map<int, int> foo = {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};
and std::map<int, int> bar = {{2, 0}, {4, 0}, {5, 0}};
是foo的子集。
由于元素在map中排序,我认为
从foo中的bar中找到第一个元素,然后找到连续的元素
从foo中的那个位置。
Since the elements are sorted in map, I would think to find the first element from bar in foo, and then find consecutive elements from bar in foo from that location.
这里的问题是我不能找出一个办法做到这一点STL地图在cpp 。
我可以将地图中搜索范围从地图中的某个位置减少到地图结尾吗?
The problem here is I'm not able to figure out a way to do that with STL maps in cpp. Can I reduce the search range in map for every find from a location in map to the end of the map?
我希望我解释了这个问题。 / p>
I hope I explained the problem.
推荐答案
使用 std :: includes
算法与自定义比较器仅比较键:
Use std::includes
algorithm with a custom comparator that compares only the keys:
#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;
});
}
这篇关于查找一个地图是否是另一个地图的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!