Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a vector of pointers

Tags:

c++

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.

like image 880
excray Avatar asked Jul 21 '11 11:07

excray


People also ask

Can you copy pointers?

Copying a pointer does not copy the corresponding object, leading to surprises if two pointers inadvertently points to the same object. Destroying a pointer does not destroy its object, leading to memory leaks.

Can you have a vector of pointers?

You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.


2 Answers

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).

like image 73
visitor Avatar answered Sep 28 '22 16:09

visitor


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;
}
like image 36
Seb Holzapfel Avatar answered Sep 28 '22 14:09

Seb Holzapfel