Copy pointer vector

I have std::vector<A*>one that I need to copy to another vector using A::Clone().

Instead of using handwritten loops, I was wondering if I could use for_eacheither any standard library algorithm for this.

+5
source share
3 answers

The corresponding algorithm is std :: transform , and you can include a member function call in 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 already has the same size as the input range, you can pass vec2.begin()as the third argument. Use back_inserterif the target is empty (or you want to add to it).

+10
source

, - :

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;
}
+3

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

This is a template parameterCloneAllocator for which you can pass the corresponding custom cloner.

+2
source

All Articles