D
D
Daniel Demidko2018-11-19 18:35:56
C++ / C#
Daniel Demidko, 2018-11-19 18:35:56

How to pass a dereference operator to a function?

There is a container with pointers, it needs to be converted to a container of objects, that is, just dereference each pointer. Right now I'm doing it with transform and a lambda.

vector<GameObject> ToVector(
    const set<GameObject*, DereferenceCompare<GameObject, greater>> &cont)
{
    vector<GameObject> res(size(cont));
    transform(cbegin(cont), cend(cont), begin(res), [](GameObject *const p) {
        return *p; 
    });
    return res;
}

Is there a way to shorten the code even more, maybe there is some standard function that dereferences the pointer?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2018-11-19
@vt4a2h

In short, it will only be with the range library (from boost, or range-v3).
By the way, you need to check the pointer for null, at least with an assertion, if you are sure that there are always valid pointers there.
Also, you are essentially copying objects. It is expensive. If this was not planned, then I advise you to use smart pointers or reference_wrapper. In addition, in modern C++ there is almost no need to use raw pointers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question