Bloomberg LP Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
I think one of the main advantages is that vector automatically frees allocated memory while you can forget to do this in case of c array leading to memory leaks..
Vectors have flexible size, C array has constant size.
When we pass a C Array to a function, we have to pass the size of the array also. Vectors know their size.
Vectors have options whereby we do not cross over the boundaries.
Every time Vectors need to increase their size, the system does it for us. This increment is based on some algorithm and is optimized. With C array it is left to us to determine how much to increase the array size. Generally speaking we cannot do as good an estimate as the program.
Because Vector is a class and C array is not, Vector users benefit from all the advantages of the class. The advantages of the class include inheritance, encapsulation, polymorphism, overloading, etc.
A vector has an underlying array, because the specification requires the use of a block of continuous memory. Which is what a C array would be.
How is vector more efficient than a C array? It's not! A vector introduces overhead due to various checks upon its method calls. For example, it checks whether it needs to grow. If you use a plain array, which is basically a chunk of continuous memory, you will access it very directly with no frills, resulting in slightly better performance.
Vector is a well-designed data structure that takes care of many edge cases that char* would have failed at (or coded manually):
- Sudo Man March 31, 2012push and pop (tail only)
resize
reverse iteration (can retur a reverse iterator)
There are other goodies but those ones are major operational benefit that wins over array.
The Vector has more memory usage than a corresponding-size array due to its overhead and memory reserveration for expansion.
The c array can be very efficient when used correctly but it is quite difficult to do that.
A veteran c programmer can probably do resize, garbage collection, push/pop and other operation on the fly and claim it's so much more efficient that everybody should do it. but how much time does it take him to code all these? Manager don't like to wait, nor customers.
It's a choice, not a rule. I would explain this to interviewer and if he still not happy with using a Vector, I tell him I will make an effort to learn c array prior to start. That should be safe.