C++ vector at() method

#include <iostream>
#include <vector>

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

    // Accessing elements using the at() method
    for (int i = 0; i < numbers.size(); ++i) {
        std::cout << "Element at index " << i << ": " << numbers.at(i) << std::endl;
    }

    return 0;
}

Explanation:

  • #include <iostream>: Includes the input/output stream library in C++.
  • #include <vector>: Includes the vector library in C++ for using vectors.
  • int main() { }: The main function where program execution begins.
  • std::vector<int> numbers = {1, 2, 3, 4, 5};: Declares and initializes a vector named numbers containing integers 1, 2, 3, 4, and 5.
  • for (int i = 0; i < numbers.size(); ++i) { }: Starts a loop to iterate through the vector elements.
  • int i = 0;: Initializes a variable i as 0.
  • i < numbers.size();: Checks if i is less than the size of the vector numbers.
  • ++i: Increments i after each iteration.
  • std::cout << "Element at index " << i << ": " << numbers.at(i) << std::endl;: Prints the element at index i using the at() method of the vector numbers.
  • return 0;: Indicates successful program execution.