Reputation: 1014
how to loop in sync over 2 maps?
it could be that either map1 or map2 contains more keys.
how do i set the preference? and increment the corresponding iterator?
example values of 2 maps:
4 7 10 11 12 13 14
3 4 7 8 10 11 12 13 14
map1 doesn't contain a '3'
What's the best way to iterate over two or more containers simultaneously
std::map<int, int> map1;
std::map<int, int> map2;
auto itA = begin(map1);
auto itB = begin(map2);
while(itA != end(map1) || itB != end(map2))
{
if(itA != end(map1))
{
++itA;
}
if(itB != end(map2))
{
++itB;
}
}
using this code would result that you try yo compare 2 unequal numbers / values.
so you must halt incrementing one or the other iterator until both value are equal.
Upvotes: 0
Views: 145
Reputation: 1014
i found the answer:
if(map1.first == map2.first){
if(itA != end(map1)){
++itA;
}
if(itB != end(map2)){
++itB;
}
}
else if(map1.first < map2.first){
if(itA != end(map1)){
++itA;
}
}
else if(map1.first > map2.first){
if(itB != end(map2)){
++itB;
}
}
Upvotes: 1