std::vector

std::vector is a dynamic container that can be used with offsets. Unlike static arrays, it can grow and shrink in size at runtime, but you can use offsets as well as iterators to navigate on them.

Some key points about std::vector

  • Dynamic resizing: When you add elements to a std::vector, it can automatically resize itself to accommodate the new elements.
  • Random access: You can access any element of a std::vector using its index, just like a regular array.
  • Efficient insertion and deletion: Inserting or deleting elements at the end of a std::vector is very efficient.
  • Memory management: std::vector handles memory management for you, so you don’t have to worry about allocating and deallocating memory manually.
  • Iterators: std::vector provides iterators that allow you to iterate over its elements in a convenient way.

Example of std:vector in C++

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers;

    // Add elements to the vector
    numbers.push_back(1);
    numbers.push_back(2);
    numbers.push_back(3);   


    // Access elements using   
 their indices
    std::cout << numbers[0] << std::endl;
    std::cout << numbers[1] << std::endl;
    std::cout << numbers[2] << std::endl;

    // Iterate over the elements using a for loop
    for (int number : numbers) {
        std::cout << number << std::endl;
    }

    return 0;
}

It will output 1,2,3 and 1,2,3.

Differences between std::vector and std::list

Featurestd::vectorstd::list
Underlying data structureDynamic arrayDoubly linked list
Random accessYesNo
Insertion/deletion at the beginning/middleInefficient (O(n))Efficient (O(1))
Insertion/deletion at the endEfficient (O(1))Efficient (O(1))
IteratorsRandom access iteratorsBidirectional iterators
Memory usageGenerally more compactGenerally less compact (due to pointers)
Export to Sheets

std::vector is often preferred due to random access and memory efficiency, while std::list if the choice if you often need to insert at the beginning or in the middle.

Leave a Reply