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!
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.)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With