excray
excray

Reputation: 2858

Copying a vector of pointers

I have a std::vector<A*> which I need to deep copy to another vector using A::Clone().

Instead of using handwritten loops, I was wondering whether I could use for_each or any Standard Library algorithm for this.

Upvotes: 5

Views: 2484

Answers (3)

Seb Holzapfel
Seb Holzapfel

Reputation: 3873

Perhaps something like this would work:

class DeepCopy {
public:
    A* operator() (A* aP) {
        return aP->Clone();
    }
}

int main() 
{
    vector<A*> vA;
    vector<A*> vA2;

    transform(vA.begin(), vA.end(), back_inserter(vA2), DeepCopy());

    return 0;
}

Upvotes: 3

visitor
visitor

Reputation: 1801

The appropriate algorithm is std::transform and you can turn member function invocation into a unary functor with std::mem_fun

Example:

#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>

class X
{
public:
    X* clone();
};

int main()
{
    std::vector<X*> vec1, vec2;
    std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2), std::mem_fun(&X::clone));
}

If the target vector is already the same size as the input range, you can pass vec2.begin() as the third argument. Use back_inserter if the target is empty (or you want to append to it).

Upvotes: 10

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

You could use boost::ptr_vector<A> instead of std::vector<A*>.

This has a template parameter CloneAllocator, for which you could pass the relevant custom cloner.

Upvotes: 2

Related Questions