TralexCpp
TralexCpp

Reputation: 117

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?

Upvotes: 1

Views: 693

Answers (1)

bipll
bipll

Reputation: 11940

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.

Upvotes: 4

Related Questions