Vectors vs LinkedList in C++

Vectors vs LinkedList in C++

Definitions:

A vector is a dynamic array or a list that can easily grow and shrink in use. You can store items that can be easily added or removed. Unlike a regular array, you don't need to specify its size ahead of time, as it adjusts its size automatically when you add or remove elements.

A linked list is like a chain of boxes. Each box (called a node) contains a piece of data and a reference to the next box in the chain. Unlike an array, where data is stored in a continuous block of memory, the boxes (nodes) in the linked list can be scattered all over, but are connected by these references.

Comparison:

  • Underlying data structure:

    Vector: uses an array underneath, meaning the elements are stored in sequential memory locations.

    Linked List: uses a series of nodes, where each node has data and a pointer to the next node (and in a doubly linked list, a pointer to the previous one too).

  • Memory Allocation:

    Vector: When more space is needed, it reallocates the memory, which can be expensive. This reallocated memory is contiguous which requires moving around existing elements.

    Linked List: Each new element in the list is a new node which is usually allocated separately. We don't have to reallocate the entire list.

  • Access Time:

    Vector: provides fast random access. Access an element at any position is O(1).

    Linked List: Access is sequential, meaning you have to traverse from the start to get to the n-th element which makes access O(n).

  • Memory Overhead:

    Vector: is more memory efficient since it just stores the element in a contiguous block

    Linked List: has additional memory overhead because of storing pointers/references with each node.

  • Insertion/Deletion:

    Vector: Inserting and deleting in the middle takes O(n) in the worst case because other elements might need to be shifted. However, if adding/removing at the end it takes O(1)(amortized).

    Linked List: Insertion/deletion is quick O(1) if we know the reference or iterator to the node otherwise we might have to traverse the list to find the node making it O(n) time.

  • Cache Friendliness:

    Vector: tends to be cache-friendly due to it's contiguous memory layout.

    Linked List: less cache-friendly because nodes are scattered throughout memory.

In Summary:

Use a vector if:

  • You need fast random access.

  • Your primary operations are adding/removing from the end.

  • You care about memory usage and cache efficiency.

Use a linked list if:

  • You frequently need to insert or delete elements in the middle.

  • You don't need fast random access to elements.

  • The potential memory overhead of the list pointers isn't a concern.

    Hope it helped. Share your thoughts!!