std::vector (And std::copy())

Basics

  • C array drawbacks

    • C arrays are fixed-size

    • Once allocated, they cannot change size

    • ⟶ rather unflexible

    • std::vector<> to the rescue

  • std::vector: Commonalities with C arrays

    • Lies in contiguous memory ⟶ efficient CPU cache usage

    • Index based access (a[2])

    • Pointer arithmetics via STL iterators

  • std::vector: Differences from C arrays

    • Can grow dynamically (push_back(), emplace_back(), …)

    • All sorts of manipulation; e.g. inserting and removing elements at any position

    • Can also shrink if you tell it to (shrink_to_fit())

Dynamicity Details

STL Iterators: Pointer Arithmetic On A std::vector<>

  • Index based iteration is cumbersome/loud

  • Remember the beauty?

    ../../../../../../_images/40-10-00-pointer-begin-end1.svg
    while (begin != end) *begin++;    // <--- beauty!
    
  • Difference: begin and end pointers are STL iterators

    C array

    std::vector

    int a[] = {100, 200, 300};
    int *begin = a;
    int *end = a + 3;
    
    std::vector<int> a = {100, 200, 300};
    std::vector<int>::iterator begin = a.begin();
    std::vector<int>::iterator end = a.end();
    

    Much typing ⟶ see C++11 auto keyword

  • Alternative to pointer-loops (but not always applicable): range based for

Algorithms And Containers : std::copy

  • std::vector<> is a generalized array

  • Why not use std::copy() on it?

  • Copy std::vector to C array

  • Copy C array to std::vector

  • Any mixture possible

  • A number of pitfalls though

  • allocation! For example …

    • Preallocate destination vector

    • Use std::back_insert_iterator