Eric Lilja wrote:
Hello, I have a std::vector storing pointers to objects that are dynamically
allocated. When I am done with the vector I want to delete all pointers. Can
I use std::for_each() or something to do that in one line? I am so tired of
seeing the following in my code:
for(vector<some_type>::size_type i = 0; i < myvec.size(); ++i)
do_something_with_each_element;
Try it, why doncha?
-------------------------------
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
struct my_class {};
struct my_alloc {
void operator()(my_class*& p) { p = new my_class; }
};
struct my_dealloc {
void operator()(my_class*& p) { delete p; p = 0; }
};
int main() {
std::vector<my_class*> v(5, (my_class*)0);
std::copy(v.begin(), v.end(),
std::ostream_iterator<my_class*>(std::cout, " "));
std::cout << std::endl;
std::for_each(v.begin(), v.end(), my_alloc());
std::copy(v.begin(), v.end(),
std::ostream_iterator<my_class*>(std::cout, " "));
std::cout << std::endl;
std::for_each(v.begin(), v.end(), my_dealloc());
std::copy(v.begin(), v.end(),
std::ostream_iterator<my_class*>(std::cout, " "));
std::cout << std::endl;
}
-------------------------------
V