Interesting C++ Notions

Hey there!

Been really busy with coding and projects these past few days so no updates. But I have learned a lot of cool new stuff which I now wish to share with you.

Let’s dive in: I am guessing you remember what a stringstream is? If you don’t, there is an old post that I have explaining its super-utility. Once you can get your head wrapped around it, one interesting thing to note is how to clear the stream. On careful scrutiny of the API, you find it has 2 methods, flush() and clear(), which you may think might get the job done. Well, turns out both are quite misleading. The flush() command is actually used to synchronize the stream buffer so that it writes any unwritten characters on the next opportunity it gets, and the clear() command is actually used to reset the flag bits associated with the stream. Thus, none of them achieve our basic objective of clearing the stream.

The answer is actually in the constructor. The str() method is the way to go. Simply call ss.str(“”) and ss.clear() to reset any fail bits (where ss is my stringstream variable), and there you have it.

Another neat trick is that of manipulator functions. We use endl when dealing with cin and cout. Turns out, you’ve been using a manipulator function all along. Other uses include printing decimals in scientific notations and changing the base of your output/input.

Probably the most useful of all the ideas here is the use of a comparator function in the sort function. The template of sort() is sort(start_iterator, end_iterator, comparator_func) and we don’t usually use this form simply because of the awesome overloaded capabilities of the sort() function. However, this form gives us greater control over our execution and I have personally used innumerable times.

The comparator function takes 2 parameters of the same type as the list to be sorted. We return true if the first parameter goes before the second and false otherwise. Thus, this allows us to define the comparison criteria for user types like classes and structs. 😀

A final trick that I would like to mention is the transform function. A handy tool for performing various transformative operations on lists, the most basic being changing the case of strings. This one needs some memory to remember the manipulator functions, but I am sure you can handle it.

Hope this helps you write more succinct, poignant code in the future.

Till then, eviva!