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 namednumbers
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 variablei
as 0.i < numbers.size();
: Checks ifi
is less than the size of the vectornumbers
.++i
: Incrementsi
after each iteration.std::cout << "Element at index " << i << ": " << numbers.at(i) << std::endl;
: Prints the element at indexi
using theat()
method of the vectornumbers
.return 0;
: Indicates successful program execution.