[英]Build a vector as a subset of another one without copying
設v
是向量。 我想w
是的一個子集v
指數之間的from
和to
。 我可以這樣做
std::vector<T> w(v.begin() + from, v.begin() + to);
但是,我不打算將來使用v
。 因此,我不需要在from
和to
之間復制數據。 我需要創建一個指向v.begin() + from
的向量,並且長度to - from
。 應該釋放v
使用的其余內存。 請注意,我很好,如果它是v
被重新定義(我只是交換到w
之后,如果我想反正)。
有可能嗎?
如果要使用vector
,則無法避免復制。 如果你想確保釋放未使用的內存,你可以這樣做:
std::vector<T> w(v.begin() + from, v.begin() + to);
std::vector<T>().swap(v);
這應該是矢量的技巧。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v{ 11, 22, 33, 44, 55, 66, 77, 88, 99 };
constexpr size_t from = 3;
constexpr size_t to = 7;
if(to < v.size() - 1)
v.erase(v.begin() + to, v.end());
if(from > 0)
v.erase(v.begin(), v.begin() + from - 1);
v.shrink_to_fit();
for(auto i : v)
cout << i << ' ';
cout << endl;
}
您應該使用std :: deque,並將所有元素從begin()跳轉到begin()+ front,從end()跳到end()。 這樣就可以從第一個存儲桶的前面和最后一個存儲桶的末端中釋放出來的內存減去一小部分內存。 std :: deque非常高效,因為它將其內容存儲在數組桶中。 它不僅僅和矢量一樣高效,但它實際上可能足夠好,因為它只有一個額外的間接層。 大致這是不同的:
參考: https : //en.cppreference.com/w/cpp/container/deque
它取決於你增長和縮小你的向量,但deque縮小和增長,而不是復制任何元素,它只是桶分配/釋放。 因此,在某些情況下,它可以比矢量更高效。
應該很快就會推出。 在此期間,您的選擇是:
使用std::string<T>
而不是vector
,因此使用std::string_view
。
制作自己的視圖類。 說,
template<class Iterator> class view { Iterator b, e; public: view(Iterator b, Iterator e): b(b), e(e) {} auto &operator[](std::size_t i) { return *(b[i]); } auto const &operator[](std::size_t i) const { return *(b[i]); } auto begin() const { return b; } auto end() const { return e; } auto size() const { return e - b; } };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.