简体   繁体   中英

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. 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?

This can be done even with plain STL, using few standard types, reference_wrapper being one particularly important:

#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 . fv stores but references to the original elements, namely, to odd-valued elements of cv , so no copies are performed.

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