Common functions implemented using STL

Posted by chunyang on February 8, 2020
TAGS: #cpp


STL provides a lot of useful utilities. They can be used to implement interesting functions.

  • This is a collection of this *

Count lines

int count_lines(string& file) {
    auto fd = ifstream(file.c_str();
    return count_if(
         [](c)->bool {return c == '\n';}

Please note that: istream_iterator won’t work here. Stackoverflow

Normally when you care:

  • formatted output, e.g. int/double, then use istream_iterator
  • unformatted input, raw bytes, use istreambuf_iterator

The same applies to ostream_iterator and ostreambuf_iterator.

String trim

void trim_left(string& input, function<bool(char)> fn) {
        find_if(input.begin(), input.end(), [&](char c) {return !fn(c);})

void trim_right(string& input, function<bool(char)> fn) {
        find_if(input.rbegin(), input.rend(), [&](char c) {return !fn(c);}).base(),

The base() function call is used to get the underlying iterator.

string a = "";
std::reverse_iterator<std::string::iterator> ite = a.rbegin();

Convert case

string to_upper(string input) {
    transform(input.begin(), input.end(), ::toupper);
    return input;

string to_lower(string input) {
    transform(input.begin(), input.end(), ::tolower);
    return input;

Split and Join strings


template<typename Iterator, typename Pred>
void filter(Iterator beg, Iterator end, Iterator out, Pred p) {
    copy_if(beg, end, out, p);


template<typename Iterator, typename Proc>
void map(Iterator beg, Iterator end, Iterator out, Proc p) {
    transform(beg, end, out, p);


template<typename Iterator, typename Reduce, typename T>
T reduce(Iterator beg, Iterator end, T initial, Reduce r) {
    return accumulate(beg, end, initial, r);

Creative Commons License
This work is licensed under a CC A-S 4.0 International License.