简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM