mrmclovin
mrmclovin

Reputation: 1123

Can I pass a std::vector<std::unique_ptr<T>> as a vector of raw pointer without extra allocations?

Suppose I have the following function:

void sum(const std::vector<int*>& input) {
  return ... ; // the sum
}

I store a vector of int pointers somewhere

...
std::vector<std::unique_ptr<int>> my_ints;

Is there a way to pass my_ints to sum() without any extra allocations such as an intermediate vector of the unique_ptrs converted to a vector of raw pointers?

Obviously, I could refacor sum() to take a vector of unique ptrs instead. Or overload it. But I'm hoping to find a way where I don't have to, and let the user decide whether or not to use a vector of unique_ptrs or raw pointers.

Upvotes: 1

Views: 380

Answers (2)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33944

Not like you want, but you should think about sum() differently. It looks like an algorithm that operates on a range, so you should make it more like this:

template <typename It>
ValueType sum(It begin, It end) {
    // ... iterate and calculate sum
    return sum;
}

Then suddenly, you can start to use ranges to do cool things!

std::vector<std::unique_ptr<int>> my_ints;
auto range = my_ints | ranges::views::transform
(
    [](auto smart_ptr) {
        return smart_ptr.get();
    }
);

This is a range that will transform as you use it! Then you could enter it into your sum() like this:

auto my_sum = sum(std::begin(range), std::end(range));

Also look up std::accumulate(), which does what you want here, I would say.

Upvotes: 4

Mooing Duck
Mooing Duck

Reputation: 66971

No, there is absolutely no way to pass those pointer values to that sum method without changing the method.

Upvotes: 1

Related Questions