[英]How would one store the result of filtering a vector inside another vector without copying
在C ++中:假設我有一個向量const std:vector<MyStruct>
,它(及其元素)不再被修改。 現在我想基於一些謂詞過濾這個向量並將結果存儲在某個對象中,因為我想經常迭代這個元素子集。
有沒有一種好方法可以避免將MyStructs
從向量復制到另一個向量中,如何做到這一點?
即使使用普通STL也可以使用少量標准類型, reference_wrapper
是一個特別重要的:
#include <iostream>
#include <vector>
#include <functional>
#include <iterator>
#include <algorithm>
int main() {
std::vector<int> cv{0, 1, 2, 3, 4, 5};
std::vector<std::reference_wrapper<int>> fv;
std::copy_if(cv.begin(), cv.end(), std::back_inserter(fv)
, [](int x){ return x % 2; });
for(auto const &v: fv) std::cout << v << '\n';
std::cout << "-----\n";
cv[3] = 42;
for(auto const &v: fv) std::cout << v << '\n';
}
$ g++ meow.cpp && ./a.out
1
3
5
-----
1
42
5
注意cv
中的變化如何反映在fv
。 fv
存儲但是對原始元素的引用,即對cv
奇數元素的引用,因此不執行復制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.