Thursday, January 6, 2011

Elegance of STL



What could be a simple example as an answer to the question "Why anyone should use STL?" I think the answer should be given in a comparative way. Lets say, someone asks you to
"take some unknown number integers as input. Then shuffle the integers and then print those back as output".
Without using STL , the whole thing would be messy (kindof). You will have to take the integers from standard input until eof is reached, then you will have to manually write a shuffle function to shuffle them and then you will have to print those back to the output. Someone with a little C++ experience can discern how many lines of code he has to write. But with STL, the same thing can be done in pretty elegant and clean way.

1. Take a std::istream_iterator (cin) which iterates on inputs taken from cin
2. take a vector where you will have to copy all the integers from cin iterator
3. Copy the whole input stream iterated values into the vector using std::copy();
4. use std::random_shuffle() function to shuffle them
5. copy the vector with shuffled numbers back to ostream_iterator (cout) where those will be printed out with given delimiter.

The code looks like this :



0 comments: