Home > Blockchain >  Can I pass a std::vector<std::unique_ptr<T>> as a vector of raw pointer without extra al
Can I pass a std::vector<std::unique_ptr<T>> as a vector of raw pointer without extra al

Time:01-19

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.

CodePudding user response:

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

CodePudding user response:

Not like this, but you should think about sum differently. It looks like an algorithm that operates on a range, so you should make it 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:

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

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

  • Related