A Basic Command-Line Parser in C++

Most of the OpenCV programs that I have written so far require explicitly taking some input from the user as a command-line argument. For example, it is highly likely that a OpenCV program would require an image (or video) to operate upon and hence requires a path to that multimedia file as an input. Instead of having the user type in the path in response to a program-generated prompt after the code has begun it’s execution, it is much more orderly, compact and convenient to supply those parameters as command-line arguments and have the logic to parse the input parameters embedded in our code.

For this exact purpose, I wrote a small, minimalist command-line parser in C++ that works out-of-the box with OpenCV programs.

The functionality of the parser is bestowed upon by three functions which are described in detail:

  1. void setCommandOptions(vector<string>& args, int argc, char** argv)

    The parameters argc and argv the variables through which the command-line arguments are actually passed down into the main() function where argc is the number of strings (arguments) pointed to by argv. This function does the simple task of copying all the command-line arguments from argv into the vector of strings named args. The for loop starts from 1 nbecause, by default the first argument in argv (corresponding to the index 0 i.e. argv[0]) is the name of your executable. For example, if I run a C++ program by executing ./myprogram arg1 from the terminal, argv[0] points to “myprogram” whereas argv[1] would point to “arg1”.

  2. string getCommandOptions(const vector<string>& args, const string& opt)

    The primary aim of this function is to retrieve the arguments corresponding to the command-line option opt (the 2nd argument to the function). So, if the program was invoked using the command ./sample-code -image ~/Pictures/picture.jpg, then the function call getCommandOptions(args, “-image”) would return the string “~/Pictures/picture.jpg”. Note that “-image” is the option and “~/Pictures/picture.jpg” is the argument here. The implementation uses the find() function from the <algorithm> header to accomplish the task along with certain sanity checks as to whether the option opt exists or not and ensuring that there is a argument corresponding to the sought after option. That is, in cases like ./sample-code -image , a function invocation of the form getCommandOptions(args, “-image”) would return an empty string because of the absence of a argument with the “-image” option.

  3. bool doesCmdOptionExist(const vector<string>& args, const string& opt)

    A predicate to check whether the command line option opt exists in args.

The complete code can be viewed here.


The BookMyShow Fiasco

My batch-mates and I decided to catch Interstellar in Dehradun on the 14th of November. One of the things I hate about Roorkee is the absence of a good multiplex nearby. The nearest theater is Wave Cinemas in Bahadrabad, but that only screens Bollywood flicks. To satiate our appetite for the occasional Hollywood movies, we have to indulge ourselves in a 2 hour bus journey to Doon! So, here we are, a merry group of 7 friends, excited about the prospects of some Nolan powered intellectual orgasms! But, we got a little more than we bargained for. Little did I know, that 12 hours after we started off from Roorkee, I would be writing this angry email to BookMyShow, the contents of which I am reproducing in this blog post.


I had booked 7 tickets for Interstellar, 4:50 PM show on the 14th November (Booking ID : GLDD0000647080) at Glitz Cinemas, The City Junction Mall, Dehradun. I received an email as well as a S.M.S. confirmation for the same. We reached the venue (Glitz cinemas) to collect our tickets from the box office with sufficient time to spare (like the punctual and responsible people we are), only to realize that we were handed printed tickets to the movie “Kill Dill”. We immediately pointed out the mistake to the guys at the ticket counter and they cross-referenced, double checked, triple checked our Booking IDs and then called in the manager who cross referenced, double checked and triple checked our bookings again. All this while, we were waiting patiently for the correct set of tickets to be handed over to us. The manager then proceeded to inform us, to our utter dismay, that Glitz was not screening Interstellar at all. Naturally, we were heartbroken (talk of “Kill Dill”, huh)! After each of us had passed through the seven stages of grief, we ruled out watching Kill Dill. I think  you would agree that it would be utter blasphemy to replace Nolan with Aditya Chopra. No sir, not in this, or any of the parallel universes can this happen. Thankfully, the manager was co-operative and promptly returned the money for the 7 tickets (Rs. 1680/-) in cash and we were on our way.

FYI, we are residents of Roorkee which is more than 70 kms from Dehradun, a 2 hour bus journey on a road which is not really meant for F1 races, if you know what I mean. We wanted to see a movie on time travel, not spend the entirety of our time on travel. I have immense respect for you guys, but when such incidents happen with names like BookMyShow, it sort of makes you lose faith in the sanctity and authenticity of online transactions! I request to arrange for the reimbursement of the “Internet Handling Fees” amounting to Rs. 196.63/- when clearly all the “handling” of the predicament bestowed upon us by the “Internet” was done by us and the travel expenses amounting to Rs. 1120/-.  #RefundMyShow

Hoping to hear from you guys very soon!

Things did not sort themselves out after this though. There wasn’t any response form their side for about more than a week, after which I had to fire another angry email. But this time, they were prompt with their replies and within the next few days, I had received the reimbursement! What surprised me though was that such an incident could happen with someone like BookMyShow. This was not the first time that online transactions had deceived us and left us in an uncomfortable situation. About a year back, 4 of my friends had planned a trip to Shimla and we had made our hotel reservations through an online portal named Travelguru. Upon reaching our destination, we found, to our utter dismay that the hotel authorities failed to identify any association of theirs with Travelguru. Thankfully, mid-January was not the busiest time of the year for tourists in Shimla and we were able to find rooms in the same hotel. But, it did involve a lot of convincing, reprimanding, threatening – all of which left a bad taste in our mouths.

These two separate incidents have one very subtle implicit similarity between them. Both of them involve a broken connection between people and technology. Although Dehradun cannot be considered as rural or even semi-urban, but from my limited experiences with Glitz cinemas, the majority of the audience that it caters to still finds solace in the traditional and orthodox stand-in-a-queue-and-book tickets method. While the situation in Shimla on the technology front was even more dire. The hotel manager, at one point of time made his discontentment and qualms with online booking pretty evident by saying that the soft-copy of a PDF file does not count as a reservation. The metropolitan cities might have stood witnesses to the widespread infiltration of the world wide web and technology into all spheres of life, but when it comes to the slightly less urbanized cities (mind you, we do not need to go down to villages, as is clear from my examples), we still have a long way to go!

Google’s Project Loon and Zuckerberg’s noble initiative of bringing internet to the villages are all commendable, but what really is required is training. Training of those people who would be directly or indirectly affected by this advent of internet. We would be able to reap the fruits of benefit only when we are successfully able to alleviate man’s deep distrust for the unknown.

My Experiences with System Design Interview Questions

I faced system design questions  while interviewing for both Google and  Directi, co-incidentally during my final round of interview for both  companies. Personally, I feel that these questions make up for an  excellent measure to gauge a candidate’s knowledge and software  engineering skills. You should treat these problems as discussions and not as your conventional interview questions. In contrast to algorithmic problems which have a consistent and clear approach to a solution (or solutions), system design questions tend to be very open-ended. The interviewer may often consciously make room for ambiguities as a test of your design skills. From what I’ve learnt during my interview process, there are some points which you should keep in mind, while tackling system design problems.

Keep it simple, stupid (KISS)!

At the very outset, you should ensure that all the system requirements, design goals, optimization objectives are crystal clear before you proceed to brainstorm on possible solutions. As an example, suppose you are asked to design a minimalist text editor using appropriate data structures. A bad approach would be to straight-away start with advanced concepts such as tries. Agreed, tries are optimized for fast insertion and search, but you need to ask yourself, “Is that really required for a minimalist editor”. It is always a good idea to note down all the data structures you know and write the pros and cons of using each one of them in the problem domain at hand. This not only clears your thought process, but also ensures that you do  not over-complicate things. You will be surprised to know how many seemingly complicated systems can be implemented using data structures which are as simple and elegant as linked lists and stacks!

Divide and Conquer

The problem statements might seem overwhelming at first, but there is absolutely no need to panic. Design questions are supposed to do look intimidating! You are expected to break the problem into modules and tackle each one of them independently. The problems that are generally asked are such that they can be easily decomposed into such fragments and solving the individual sub-problems should be a matter of reducing them to a known algorithm. For example, if I am supposed to design a technique to compress log records (lossless compression), my approach would be to first decide on what kind of fields a log record might contain and then think about efficient ways of compressing each one of them. Date and time can be stored as seconds elapsed since the beginning of the year (assuming we are interested in logs that are not more than a year old, this should fit in a 32 bit integer), verbose error descriptions can be replaced by short error codes which are mapped to their respective descriptions on a separate hash map, and so on!

Think out loud

Another very important strategy is to always keep communicating with your interviewer. As stated earlier, system design questions do not have a 0-1 answer. Whatever solution you proffer, there is always scope for optimizations. In such a scenario, it is imperative to let your interviewer have a glimpse of your thought process. Though this advice is true in general for the entire spectrum of question formats, it holds special significance here. Following this has the added benefit of the fact that the interviewer would be able to correct you if you digress from the intended path and he may have some ideas that you can further build upon in your solution.

Knowledge is power

Since, the systems that you would be asked to design are most likely going to be a simplified prototype of a commercial  system, you might end up having to use some Machine Learning or Data Science in your solution. So, it’s a good idea to brush up on some common M.L. and N.L.P.  concepts before your interview! If you are asked to implement the “Did you mean” feature in Google search, in addition to everything else, it wouldn’t hurt you to know about how spelling correctors work (N.L.P.)!

P.S. : This was originally posted as a Quora answer to this thread.