I've got a vector<MyType>
and would like another vector<MyType>
containing only those MyTypes which fulfill some simple criteria, e.g. that some data member equals something. What's the best way to solve this?
Use copy_if
:
#include <algorithm> // for copy_if
#include <iterator> // for back_inserter
std::vector<MyType> v2;
std::copy_if(v1.begin(), v1.end(), std::back_inserter(v2),
[](MyType const & x) { return simple_citerion(x); } );
Using a little bit of Boost, you can:
std::vector<int> v = {1,2,-9,3};
for (auto i : v | filtered(_arg1 >=0))
std::cout << i << "\n";
This sample uses Phoenix for implicit lambdas defined by expression template (_arg1 >= 0
), but you can use any callable (C++03 or higher) with Boost adaptors (fitlered, transformed, reversed etc)
See here for more showcase material and a full example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With