2

Possible Duplicate:
C++ STL: Which method of iteration over a STL container is better?

In my current project, I have an STL Deque of pointers. I also have a method that is meant to delete all of the objects that those pointers are pointing to. I've come up with two different ways to achieve this, but I can't decide which is the preferred method.

Method 1.

for (deque<MyType*>::const_iterator it = myDeque.begin(); it != myDeque.end(); ++it)
{
    delete *it;
}

myDeque.clear();

Method 2.

for (int i = 0; i < myDeque.size(); ++i)
{
    delete myDeque[i];
}

myDeque.clear();

Both of these methods should work, but which one would be preferred? Method 1 makes use of the STL, but Method 2 is much simpler. Other than code cleanliness, is there any reason why one method should be used over the other? Is there any advantage to using an iterator in this scenario despite the little bit of overhead that goes into creating it?

Note: This question applies to other STL sequence containers, not just Deques.

Community
  • 1
  • 1
Matt Flowers
  • 800
  • 9
  • 12
  • In this particular case using smart pointers would be the preferred solution. – Sergey Kalinichenko Apr 29 '12 at 00:58
  • As mentioned below, the first is probably more efficient. But avoid calling end() (and size() for that matter) repeatedly by doing this: for (deque::const_iterator it = myDeque.begin(), endit = myDeque.end(); it != endit; ++it) – Anon Mail Apr 29 '12 at 04:53
  • @Anon - Any local optimization you attempt here is likely to be noise compared to the `delete` call. – Bo Persson Apr 29 '12 at 06:19
  • @Bo That's true. But not calling the end() function for each iteration is good practice. It's like incrementing the iterator with prefix instead of postfix oprator. It's part of my don't pessimize prematurely practices – Anon Mail Apr 29 '12 at 15:35

3 Answers3

2

Unless you really need to use a collection of pointers, just use a collection of objects and be done with it.

If you truly need a collection of pointers, then you probably want to use something like a Boost pointer container to automate deleting the pointee items.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

I would say 1 is more efficient, as incrementing is more efficient than random access. Random access requires retrieving the necessary constant and do a full addition while incrementing is often implemented very efficiently in the hardware.

But of course, initializing an iterator costs something, so there is a threshold on number of elements where iterator becomes more efficient, but I expect that number to be quite low.

guinny
  • 1,522
  • 10
  • 19
1

I don't know if there is any difference between those two methods, but I would use this:

std::vector<boost::shared_ptr<MyType*> > vec
Bo Persson
  • 90,663
  • 31
  • 146
  • 203