Reputation: 25
Check if map in C++ contains all the keys from another map answers my question but I'm not sure how we iterate through two maps at the same time.
I know how to iterate through one as shown:
typedef std::map<QString, PropertyData> TagData;
TagData original = readFileToMap("FoxHud.bak");
for (TagData::const_iterator tagIterator = original.begin(); tagIterator != original.end(); tagIterator++) {
}
Upvotes: 2
Views: 627
Reputation: 910
If you want to iterate the 2 maps simultaneously, you can do this:
if (map1.size() != map2.size())
; // problem
else
{
for (map<X,Y>::const_iterator it1 = map1.begin(),
it2 = map2.begin();
it1 != map1.end() && it2 != map2.end();
++it1 , ++it2)
{
// ...
}
}
Now if you want to iterate through the 2 maps at different "speeds", then a while loop to condition the increments of it1 and it2 independently would then be more appropriate. See Golgauth's answer for an example.
Upvotes: 0
Reputation: 10272
Try this way:
// As std::map keys are sorted, we can do:
typedef std::map<string, int> TagData;
TagData map1;
TagData map2;
...
TagData::const_iterator map1It = map1.begin();
TagData::const_iterator map2It = map2.begin();
bool ok = true;
std::size_t cnt = 0;
while (map2It != map2.end() && map1It != map1.end()) {
if (map1It->first != map2It->first) {
map1It++;
} else {
map2It++;
cnt++;
}
}
if (cnt != map2.size()) ok = false;
cout << "OK = " << ok << endl;
This should work with maps that are not the same size, as well.
Upvotes: 2