Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter std::vector of std::string's

Tags:

c++

boost

c++98

How can I produce an output vector which filters an input vector based on whether it starts with a certain sub-string or not. I'm using c++98 and boost.

This is as far as I got:

std::string stringToFilterBy("2");
std::vector<std::string> input = boost::assign::list_of("1")("2")("22")("33")("222");
std::vector<int> output;
boost::copy( input | boost::adaptors::filtered(boost::starts_with), std::back_inserter(output) );
like image 245
Baz Avatar asked Feb 07 '26 01:02

Baz


1 Answers

You can use std::remove_copy_if instead:

#include <algorithm>
#include <iterator>
#include <vector>

struct filter : public std::unary_function<std::string, bool> {
    filter(const std::string &by) : by_(by) {}
    bool operator()(const std::string &s) const {
        return s.find(by_) == 0;
    }

    std::string by_;
};

std::vector<std::string> in, out;
std::remove_copy_if(in.begin(), in.end(), std::back_inserter(out),
                    std::not1(filter("2")));
like image 103
Olaf Dietsche Avatar answered Feb 08 '26 15:02

Olaf Dietsche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!