检查 map<string, string> 是否包含另一个 map<string, string>

Check if map<string, string> contains another map<string, string>

我在 C++ 中有一个字符串映射,想检查第一个映射中是否包含另一个映射。例如

map<string, string> mA = {{"a", "a1"}, {"b", "b1"}, {"c", "c1"}};
map<string, string> mB = {{"b", "b1"}, {"a", "a1"}};

bool contained = isContained(mB, mA);

// isContained returns true iff every key value pair from mB is contained in mA.
// in this case is true because the pair <"b", "b1"> is contained in mA,
// and the pair <"a", "a1"> is contained too.

我更愿意使用 STL 中的某些函数,以使我的代码更清晰。

请注意,地图中没有特定的排序。

例如在java中,使用

可以很容易地解决这个问题
h2.entrySet().containsAll(h1.entrySet())

但老实说,我不知道如何用 C++ 解决它。

std::includes(mA.begin(), mA.end(),
              mB.begin(), mB.end());

这仅适用于已排序的容器,std::map 是。但它不适用于 unordered_map,例如。另请注意,这确实考虑了映射值。为了忽略它,只比较键,您可以将自定义比较传递给 std::includes.