Muhammad Zaighum
Muhammad Zaighum

Reputation: 560

Iterate multiple maps with single loop

I am trying to iterate two maps with one loop. it works fine with one map. when I add second map(see code below) it gives me error "Cannot deduce 'auto' type"

both variables are of same type.

what is the best way to iterate two maps.

 for ( auto& insertEntry = insertedInstances.begin(),
       auto& updateEntry = toUpdateInstances.begin(); 
       insertEntry != insertedInstances.end(); insertEntry++,updateEntry++
     )
 {
    //do something
 }

Upvotes: 1

Views: 2665

Answers (2)

Rakib
Rakib

Reputation: 7625

it is equivalent to

for(int i=0, j=0; i<10;i++) { //do something }

so remove the extra auto&

for ( auto insertEntry = insertedInstances.begin(),
      updateEntry = toUpdateInstances.begin(); 
      insertEntry != insertedInstances.end(); 
      ++insertEntry , ++updateEntry //pre-increment might produce better code
    )
{
  //do something
}

you can not use same type twice with comma operator.

Upvotes: 4

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

You can't have multiple type declarators inside the loop. In your case you use auto& twice. As long as both maps have the same type you could used

for (auto insertEntry = insertInstances.begin(), updatedEntry = insertInstances.begin();
     insertEntry != insertInstances.end(); ++insertEntry, ++updateEntry) {
    ...
}

(you probably don't want to use auto& in this context but auto anyway).

Upvotes: 3

Related Questions