use a linked list or a vector

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • APEJMAN
    New Member
    • Feb 2008
    • 33

    use a linked list or a vector

    In Programming is it better to use a linked list or a vector to store data?
    would you please please explain it for me
    thanks
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    It depends on what you want to do with the data you are storing.

    Vectors allow for very fast access of members - you just say, "I want this one!" and grab it. They are basically arrays with a lot of fun extra methods and properties, so using a vector is usually very simple. However, like arrays, vectors use up a contiguous block of memory - that is, if you want to store 20 integers, the vector needs to find enough room in memory for 20 ints (assuming a 4 byte integer, that's 80 bytes of memory) in a row to claim. Even worse, if you constantly use the vector's push_back method, each time the vector will need to find a new piece of memory, this time big eno0ugh to hold 21 ints...then 22 ints, 23 ints, etc. etc. This can take a while to do. Finally, removing an element from a vector means all successive elements must be moved. For instance, in your vectpor of 20 integers, if I erase the 5th integer, then the 6th integer must be moved to the 5th integer position, the 7th integer must be moved down to the 6th integer position, etc. etc.

    Lists allow for very quick removal of elements. Once you find the element to be removed, all it takes is some pointer rearranging and you're done. There is no shifting of elements necessary because lists don't hold their memory in a contiguous block. The first element of your list might be in position 273, your second element in position 48329, your third in position 1, etc. etc. None of this affects your list, because each node carries a pointer to the next. The drawback to lists is that you can't get to any given element quickly. If you want to find the 5th element, you need to first find the 4th. To find the 4th, you must find the 3rd, then the 2nd, which you can find with the head node. If you're going to be looking through the list a lot to find elements, you will slow your program down.

    Any data structure has advantages and drawbacks - it is up to the programmer (that's you!) to decide if the benefits of a data structure outweigh the costs.

    Comment

    Working...