Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 996
Andreas Avatar asked May 22 '12 22:05

Andreas


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); } );
like image 91
Kerrek SB Avatar answered Sep 29 '22 21:09

Kerrek SB


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:

  • Is it possible to use boost::filter_iterator for output?
like image 21
sehe Avatar answered Sep 29 '22 20:09

sehe