[英]Assign std::vector<std::unique_ptr<T>> to another std::vector<std::unique_ptr<T>>
[英]Can I pass a std::vector<std::unique_ptr<T>> as a vector of raw pointer without extra allocations?
假設我有以下 function:
void sum(const std::vector<int*>& input) {
return ... ; // the sum
}
我在某處存儲了一個 int 指針向量
...
std::vector<std::unique_ptr<int>> my_ints;
有沒有辦法將my_ints
傳遞給sum()
而無需任何額外分配,例如將 unique_ptrs 的中間向量轉換為原始指針向量?
顯然,我可以重構sum()
來取一個唯一 ptrs 的向量。 或者超載。 但我希望找到一種我不必這樣做的方法,讓用戶決定是否使用 unique_ptrs 向量或原始指針。
不像你想要的那樣,但你應該以不同的方式考慮sum()
。 它看起來像一個在范圍內運行的算法,所以你應該讓它更像這樣:
template <typename It>
ValueType sum(It begin, It end) {
// ... iterate and calculate sum
return sum;
}
然后突然之間,您可以開始使用范圍來做很酷的事情了!
std::vector<std::unique_ptr<int>> my_ints;
auto range = my_ints | ranges::views::transform
(
[](auto smart_ptr) {
return smart_ptr.get();
}
);
這是一個會隨着您的使用而變化的范圍! 然后你可以像這樣將它輸入到你的sum()
中:
auto my_sum = sum(std::begin(range), std::end(range));
還要查找std::accumulate()
,我會說,它在這里做你想要的。
不,絕對沒有辦法在不更改方法的情況下將這些指針值傳遞給該sum
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.