Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's your favorite STL trick? [closed]

Tags:

c++

stl

I've been programming in C++ for quite a while now, but every now and then I stumble upon a code snippet using STL that would have taken myself quite some time and a lot more code to accomplish.

STL takes quite a while to get used to, and there are not many resources out there with real-life examples on how to use it. Please share your favorite STL feature with me!

like image 920
chris Avatar asked Nov 18 '10 21:11

chris


2 Answers

Erasing certain elements from a vector in linear time with the erase-remove-idiom:

vec.erase(std::remove(vec.begin(), vec.end(), is_odd), vec.end());

(Manually looping through the vector and erasing on a per-element basis would be quadratic time.)

like image 128
fredoverflow Avatar answered Oct 14 '22 12:10

fredoverflow


dos2unix.cpp

#include <fstream>
#include <iterator>
#include <algorithm>

bool is_cr(char c) { return c == '\r'; }

int main(int, char* a[])
{
    std::ifstream is("/dev/stdin");
    std::ofstream os("/dev/stdout");
    std::istreambuf_iterator<char> in(is), end;
    std::ostreambuf_iterator<char> out(os);
    remove_copy_if(in, end, out, is_cr);
}
like image 11
chris Avatar answered Oct 14 '22 10:10

chris