Skip to content

Instantly share code, notes, and snippets.

@lancetw
Created November 28, 2020 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lancetw/83951da1c6177646b222e57b0efeef16 to your computer and use it in GitHub Desktop.
Save lancetw/83951da1c6177646b222e57b0efeef16 to your computer and use it in GitHub Desktop.
// ref: https://gitlab.com/manning-fpcpp-book/code-examples/-/blob/master/chapter-01/count-lines-transform/main.cpp
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <ranges>
using namespace std::ranges;
/**
* This function opens a file specified by the filename argument,
* and counts the number of lines in said file
*/
int count_lines(const std::string &filename)
{
std::ifstream in(filename);
// We are creating an iterator over the input stream and
// passing it to the count algorithm to count the number
// of newline characters
return std::count(
std::istream_iterator<char>(in >> std::noskipws),
std::istream_iterator<char>(),
'\n');
}
/**
* 2020 ver.
*/
auto count_lines_in_files(const std::vector<std::string>& files)
{
return files | views::transform(count_lines);
}
int main(void)
{
auto results = count_lines_in_files({"main.cpp", "Makefile"});
for (const auto &result: results) {
std::cout << result << " line(s)\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment