YetiCodeCamp - C++ for Beginners

Companion website for the C++ for Beginners YouTube video series.

C++ Vector at() Function

The C++ returns a reference to an element within the vector.


Example, using a vector ā€œv1ā€ and position ā€œpā€.;

Returns the value in the element at position p.

The following example uses a vector v1, and a position p to return a specific element.

int p = 3;
vector<int> v1 {11,12,13,14,15};
cout <<;

Output: 14

This example is a complete program using vector at() function to print the contents of a vector. We are also using the vector size() function to determine the number of elements in the vector to iterate through.


int main()  
  std::vector<int> v1{1,2,3,4,5,6};

  for(int i=0;i<v1.size();i++)  
      std::cout<< << " ";
  return 0;   

Output: 1 2 3 4 5 6