Sunday, April 1, 2007

STL vector and list Difference

If you are using STL fist time , you can see that these are the classes for holding a gropup of things.
You need to include #include <vector> and #include <list> for using these classes, also specify they are in std namespace . This can be done by using namespace std;

We all know these stuff. So what is the difference between vector and list ? When i compared the names first time , i can't see any difference, vector is something which has magnitude and direction in maths ( just joking) and list is our linked list ( doubly or single ).  No it is not like that , Actually the vector class only allows to insert in the back side or front side ( No addition in between ). But list allows.  list has function like insert() , using we can insert to any position. You may think then why we need vector? Ofcourse we need because , list costs perfomance degrade for allowing us to insertion in between the two ends. So IF you don't want to insert in between the front and last end , use vector. This can be speed up your performance.

One other difference is in vector each elements can be accesses using [] . But in list it won't possible.

These are the Key differece. In implementation wise vector is like dynamic array (When i say dynamic array u may think that "Is that same linked list ???"  , Not exactly ,the STL doc says that they have done some perfomance tuning for vector) , and list is the same linke list

1 comment:

Sarath said...

vectors are superior if we are storing data as an array. or it provides very fast access to the elements to it\'s elements
list is superior for random insertions and one more class called deque is superior when insertions happening beginning or end of the container. You can see an in-depth study of deque class at code project.