Screenplay: std::vector, And Pointer Arithmetics

  • Using raw C pointers

    #include <vector>
    #include <iostream>
       
    int main()
    {
        std::vector<int> a = {100, 200, 300};
    
        const int *begin = &a[0];              // <--- pointer to first element
        const int *end = &a[3];                // <--- pointer past last element
    
        while (begin != end)
            std::cout << *begin++ << std::endl;
    
        return 0;
    }
    
  • Generalized pointer: STL iterator

  • .begin(), .end()

    #include <vector>
    #include <iostream>
       
    int main()
    {
        std::vector<int> a = {100, 200, 300};
    
        std::vector<int>::const_iterator begin = a.begin();  // <--- looks like a pointer, but isn't
        std::vector<int>::const_iterator end = a.end();      // <--- looks like a pointer, but isn't
    
        while (begin != end)
            std::cout << *begin++ << std::endl;
    
        return 0;
    }
    
  • Simpler alternative, but not always applicable: range based for

    #include <vector>
    #include <iostream>
       
    int main()
    {
        std::vector<int> a = {100, 200, 300};
        for (int i: a)                           // <--- range based for
            std::cout << i << std::endl;
        return 0;
    }