How to limit iteration

Well, OP deleted his post, but I took the time to make a reply, so here it is.

There is, unfortunately, no past-the-end safety in iterators, just as with pointers.

Use a counter.

1
2
3
4
5
6
7
8
9
10
11
12
vector <enemy> enemies;
...

int n = 0;
for (enemy& enemy : enemies)
  if (n++ == 5) break;  // limit to a maximum of 5 enemies
  else
  {
    enemy.update();
    enemy.updateMovement();
    screen.draw(enemy.sprite());
  }

There exist much more sophisticated ways of dinking with iterators (*cough*Boost*cough*), but for a simple view at the head of the list this will do.

Hope this helps.
sorry my bad for deleting post ddnt realize it

but thank you sooooooooooooooo much it works flawlessly
hey sori to disturb again the ranged for loop u gave me works bt when i delete i enemy another enemy comes back dont know what is wrong.... dis tym i posted a code where every 1 second an enemy appears randomly please help......tanx in advance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  
 int m=0;
            m++;
            if((Timer1.asSeconds() >= 1)&&(m<=3) )
            {

                clock1.restart();
                class random randoms;
                enemy1.rect.setPosition(randoms.random_function(1000),
                                        randoms.random_function(800));
               enemyArray.push_back(enemy1);
               m=0;


            } 


int n = 0;
for (enemy& enemy : enemyArray)
{
  if (n++ == 3) break;  // limit to a maximum of 5 enemies
  else
  {

    enemy.update();
    enemy.updateMovement();
    screen.draw(enemy.sprite);
  }
}

The vector of enemies always has enemyArray.size() enemies. For example:

    { e0, e1, e2, e3, e4, e5, e6 } : seven enemies


But your original question was how to only look at the first 5 enemies:

    { e0, e1, e2, e3, e4, e5, e6 }

The enemies beyond the first five are still there. So if you delete one of the first five:

    { e0, e2, e3, e4, e5, e6 }

One of the other enemies will now be in position as one of the first five:

    { e0, e2, e3, e4, e5, e6 }


Maybe I misunderstood your original question. Do you want to make sure that there are never more than five enemies total?

Do that by only spawning new enemies when there is room.

1
2
3
4
5
if (enemyArray.size() < 5)
{
  enemy new_enemy = ...;
  enemyArray.push_back(new_enemy);
}

Then you don't need the code to limit a loop to N elements:

1
2
3
4
5
for (auto& enemy : enemyArray)
{
  enemy.update();
  ...
}

Hope this helps.
thanx dat works
Topic archived. No new replies allowed.