Wednesday, May 5, 2010

C++ style puzzles

Some interesting puzzles that can be asked in an interview.

1. Given a vector v, what is the difference between the lines marked A and B?

void f(vector& v) {
v[0]; // A; // B

If v is not empty then there is no difference between lines A and B. If v is empty, then line B is
guaranteed to throw a std::out_of_range exception, but there's no telling what line A might do.
There are two ways to access contained elements within a vector. The first, vector::at, is required to perform bounds-checking to ensure that the vector actually contains the requested element. It doesn't make sense to ask for, say, the 100th element in a vector that contains only 10 elements at the moment, and if you try to do such a thing, at will protest by throwing a std::out_of_range hissy fit (also known as an exception).

No comments: