Skip to main content

6.4) Accessing Vector Elements


  • The front method returns the element at the front of the vector
  • The back method returns the element at the back of the vector
  • Arbitrary elements can be accessed via an integer index; which is zero-based
    • Either using square brackets containing the index:
    • vector<int> v(10);
      cout << v[0] << endl;   // prints first element of v
      cout << v[1] << endl;   // prints second element of v
      cout << v[9] << endl;   // prints last element of v
      
    • Or by calling the at method and providing the index as an argument:
    • cout << v.at(0) << endl;   // prints first element of v
      cout << v.at(1) << endl;   // prints second elements of v
      
  • The difference between [ ] and the at method is that the latter does bounds checking and can signal that bounds have been exceeded by throwing an exception (see Exercise 10)