Saturday, May 22, 2010

In c++ what is the difference between vector and an array?

In C++, the STL (standard template library) "vector" type is a rich-featured template class. This means it can hold objects of almsot any type, controlling them in a rich way to do searches, sorts, etc. There are other container types as well, and most support the same operations. The differences are in the speed and optimization you get from each (searches are usually vastly different). Also see "map" and "multimap" and other associative containers.





A simple array type ( int[ ] or similar) is akin to a C array, where a fixed number of items is reserved on the heap (or stack) and you must flip through them manually with an index. There are no methods on these types for searches, inserts, deletes, etc because they are not a true "container" but simply a sequence of similar objects in memory. You must write the code to search them.





Look up the vector in the STL (see sources) and try using some of the methods it provides. There is a cost associated with using a template class from the STL, and sometimes this matters (don't use one unless you need the functionality it provides). But if you need to do searches, a vector or similar template can be a great help. Number one benefit is you don't have to debug you're code for doing set operations, you can trust the STL.

In c++ what is the difference between vector and an array?
A vector is an STL encapsulation, a container class, it can be thought of as a dynamic array.





An array is a fixed set of something.
Reply:i guess the difference would be the same as that in java (I dont know any C++), and the difference would be that an array once declared, the size of the same cant be increased, but the size of a vector automatically adjusts itself if you keep adding more elements to it


No comments:

Post a Comment