Andreas
Andreas

Reputation: 7550

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

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?

Upvotes: 8

Views: 2794

Answers (2)

sehe
sehe

Reputation: 392921

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:

Upvotes: 7

Kerrek SB
Kerrek SB

Reputation: 477010

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); } );

Upvotes: 17

Related Questions