Implement a Line Filter by Using Ranges in C++

Let’s talk about filtering lines in C++. We can filter lines in the file by some characters present in it. Here, we use library Ranges for filtering the lines if certain words are present.

For filtering, we need:

  1. split- This part of the program splits the text into lines
  2. filter- This filters the lines having that word
  3. join- This joins the filtered lines to make a new text

The code for a file having lines filtered by certain words present in them :

#include <range/v3/view/filter.hpp>
#include <range/v3/view/join.hpp>
#include <range/v3/view/split.hpp>
 
std::string const filteredText = text | ranges::view::split('\n')
                                      | ranges::view::filter(contains(controlFlowKeywords()))
                                      | ranges::view::join('\n');

bool contains(std::string const& string, std::vector<std::string> const& substrings)                  //split
{
    return std::any_of(begin(substrings), end(substrings),
              [string](std::string const& substring)
              {
                  return string.find(substring) != std::string::npos;
              });
}
 
auto contains(std::vector<std::string> const& substrings)                                             //filter
{
    return [&substrings](std::string const& string)
           {
               return contains(string, substrings);
           };
}
 
auto contains(std::vector<std::string> && substrings)                                                 //join
{
    return [substrings{std::move(substrings)}](std::string const& string)
           {
               return contains(string, substrings);
           };
}

Leave a Reply

Your email address will not be published. Required fields are marked *