return vector vs return iterator

hello, which one do you think is better?

because im looping through each vector of an object from a vector

heres the one that returns vector which i think is slow, since it has to copy
the vector of bullets to another vector here std::vector<Bullet> b = t[a].getBullets();

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
class Bullet
{

}


class Tower
{
      const std::vector<Bullet>& getBullets()
      {
          return b;
      }
  
      std::vector<Bullet> b;
}

std::vector<Tower> t;

//game loop

for ( int a = 0; a < t.size(); a++ )
{
     std::vector<Bullet> b = t[a].getBullets(); 
     for ( int c = 0; c < b.size(); c++ )
     {
          ////// process
     }     
}



and heres the second one that returns an iterator to be used in the loop:


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
31
32
33
34
35

class Bullet
{

}


class Tower
{
      std::vector<Bullet>::const_iterator getBulletBegin()
      {
            if ( b.size() > 0 ) return b.begin();
            else return getBulletEnd();
      }
      std::vector<Bullet>::const_iterator getBulletEnd()
      {
            return b.end();
      }
      
  
      std::vector<Bullet> b;
}

std::vector<Tower> t;

//game loop

for ( int a = 0; a < t.size(); a++ )
{
     for ( std::vector<Bullet>::const_iterator iter = t[a].getBulletBegin(); iter != t[a].getBulletEnd(); iter++ )
     {
          ////// process
     }     
}


so will i obtain better speed in using iterators?
Last edited on
Given that getBullets is returning a reference to t[a]'s member, you could keep referencing it without creating a local copy:

const std::vector<Bullet>& b = t[a].getBullets();

(just keep in mind that the reference will be invalidated by any structural changes, such as a push_back, made to t[a].b, and possibly changes made to t as well)

Returning a pair of iterators or another form of view is perfectly reasonable too (and those iterators will be invalidated similarly, so don't let them sit around). In fact, if you name your iterator-returning member functions "begin()" and "end(), you will be able to use range-for:

1
2
3
4
     for ( Bullet b : t[a] )
     {
          ////// process
     }   
Last edited on
@Cubbi

i didnt think of the reference XD

thanks !
Topic archived. No new replies allowed.