I need to check if a map is subset of another map. For this, I have written the following code:
#include <string>
#include <iostream>
#include <map>
using namespace std;
/**
* Checks if rhs is a subset of lhs
*/
template<class Map>
bool map_compare(Map &lhs, Map &rhs)
{
if(rhs.size() > lhs.size() || rhs.empty()) return false;
typename Map::iterator litr = lhs.begin();
for (typename Map::iterator ritr = rhs.begin(); ritr != rhs.end(); ritr++)
{
if(litr == lhs.end() && ritr != rhs.end()) return false;
while (litr != lhs.end())
{
if (litr->first == ritr->first)
{
if (litr->second == ritr->second)
{
litr++;
break;
}
return false;
}
else
{
litr++;
}
}
}
return true;
}
int main()
{
map<int, string> a, b;
a[0] = "0";
a[1] = "1";
b[0] = "0";
cout << "b ⊆ a? " << map_compare(a, b) << " (should be 1)\n";
b[1] = "1";
cout << "b ⊆ a? " << map_compare(a, b) << " (should be 1)\n";
b[2] = "2";
cout << "b ⊆ a? " << map_compare(a, b) << " (should be 0)\n";
}
I am looking for another implementation of map_compare which is either shorter or more efficient.