Reputation: 10911
I'm trying to get my coworkers to use more algorithms and less explicit loops. So my coworker has a vector of shared_ptr
s and is making a copy of that vector
and the items being pointed at. He has something like this:
dst.clear();
for (size_t i=0; i<src.size(); i++)
{
std::shared_ptr<Type> pObject(new Type(*src[i]));
dst.push_back(pObject);
}
I'm thinking that this could be better done using std::copy
with a std::back_inserter
, but I don't see how to get it to copy the items being pointed at using the stuff currently in the STL.
Could roll my own, but would think that this issue would have come up enough that it would have been dealt with by now.
Upvotes: 2
Views: 183
Reputation: 304122
There's std::transform()
:
std::transform(src.begin(), src.end(),
std::back_inserter(dst),
[](shared_ptr<Type> const& ptr) {
return make_shared<Type>(*ptr);
});
With the caveat that if Type
is polymorphic, this probably does the wrong thing and you'll want to add a clone()
method or something to that effect.
In C++20, this'll look something like:
dst = src | ranges::view::transform([](shared_ptr<Type> const& ptr){
return make_shared<Type>(*ptr);
})
| ranges::to<std::vector>;
Which you can already get with range-v3 today.
Upvotes: 6