user2773755
user2773755

Reputation: 117

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

I have a map of strings in c++, and want to check if another map is contained into the first one. For example

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.

I would prefer to use some function from the STL, to make my code cleaner.

Note that there is no particular sort in the map.

In java for example, this can be solved easily using

h2.entrySet().containsAll(h1.entrySet())

But honestly I don't know how to solve it in c++.

Upvotes: 2

Views: 195

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

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

This only works on sorted containers, which std::map is. But it won't work on an unordered_map, for example. Also note this does take the mapped value into account. In order to ignore it, and only compare keys, you can pass a custom comparison to std::includes.

Upvotes: 5

Related Questions