Passing forward iterator as parameter

  • Thread starter Michael Domenic DiBernardo
  • Start date
M

Michael Domenic DiBernardo

I posted this on comp.std.c++ because it seemed a more appropriate
question for that forum, but I'm more or less in a hurry and so I decided
to toss it out here as well:

How might I declare a function that takes a forward_iterator as a
parameter? I want a generic function that will iterate over a given
forward iterator and free all of the pointers contained therein.

The gist:

#include <iterator>

void deleteAll(std::forward_iterator begin, std::forward_iterator end) {
while (begin != end) {
delete *begin;
++begin;
}
}

Silly usage scenario (assuming existence of class MyObj):

vector<MyObj*> v;
v.push_back(new MyObj());
v.push_back(new MyObj());
v.push_back(new MyObj());

deleteAll(v.begin(), v.end());

Any tips or references would be greatly appreciated!

Thanks,
-M.D.
 
V

Victor Bazarov

Michael said:
I posted this on comp.std.c++ because it seemed a more appropriate
question for that forum, but I'm more or less in a hurry and so I
decided to toss it out here as well:

How might I declare a function that takes a forward_iterator as a
parameter? I want a generic function that will iterate over a given
forward iterator and free all of the pointers contained therein.

How would it know when to stop?
The gist:

#include <iterator>

void deleteAll(std::forward_iterator begin, std::forward_iterator

Ah, so *two* iterators, then.
end) { while (begin != end) {
delete *begin;
++begin;

Or just

delete *begin++;
}
}

Silly usage scenario (assuming existence of class MyObj):

vector<MyObj*> v;
v.push_back(new MyObj());
v.push_back(new MyObj());
v.push_back(new MyObj());

deleteAll(v.begin(), v.end());

Any tips or references would be greatly appreciated!

You _have_ to make it a template:

template<class ForwardIter>
void deleteAll(ForwardIter begin, ForwardIter end) {
... // same body


V
 
M

Michael Domenic DiBernardo

You _have_ to make it a template:

template<class ForwardIter>
void deleteAll(ForwardIter begin, ForwardIter end) {
... // same body

Guh, I totally should have figured that out on my own. Thanks so much!

This is what happens when I return to C++ after programming in OCaml for 6
months...

-M.D.
 
R

Roland Pibinger

You _have_ to make it a template:

template<class ForwardIter>
void deleteAll(ForwardIter begin, ForwardIter end) {
... // same body

This is an example of the 'templates create more templates' pinciple
in C++.
 
D

dasjotre

Michael Domenic DiBernardo wrote:
<snip>

why not use boost pointer containers instead ?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,743
Latest member
WoodrowMea

Latest Threads

Top