and would like another vector containing only those MyTypes that fulfill som...">

How to filter or "grep" a C ++ vector?

I have a vector<MyType> and would like another vector<MyType> containing only those MyTypes that fulfill some simple criteria, for example. that some data element has something. What is the best way to solve this problem?

+8
c ++
source share
2 answers

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); } ); 
+17
source share

Using a 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 example uses Phoenix for the implicit lambdas defined by the expression pattern ( _arg1 >= 0 ), but you can use any callable (C ++ 03 or higher) with Boost adapters (fit, convert, reverse, etc.)

See here for more showcase materials and a complete example:

  • Is it possible to use boost :: filter_iterator for output?
+7
source share

All Articles