简体   繁体   English

如何在不复制的情况下存储将矢量过滤到另一个矢量中的结果

[英]How would one store the result of filtering a vector inside another vector without copying

In C++: Let's say I have a vector const std:vector<MyStruct> that (and its elements) won'tt be modified anymore. 在C ++中:假设我有一个向量const std:vector<MyStruct> ,它(及其元素)不再被修改。 Now I want to filter this vector based on some predicate and store the result in some object, because I'd like to iterate over this subset of elements frequently. 现在我想基于一些谓词过滤这个向量并将结果存储在某个对象中,因为我想经常迭代这个元素子集。

Is there a good way to avoid copying MyStructs from the vector into the another vector and how would this be done? 有没有一种好方法可以避免将MyStructs从向量复制到另一个向量中,如何做到这一点?

This can be done even with plain STL, using few standard types, reference_wrapper being one particularly important: 即使使用普通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

Note how changes in cv reflect in fv . 注意cv中的变化如何反映在fv fv stores but references to the original elements, namely, to odd-valued elements of cv , so no copies are performed. fv存储但是对原始元素的引用,即对cv奇数元素的引用,因此不执行复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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