Accessing elements
Having discussed the declaration and initialization of std::vector
, our focus now shifts to accessing and manipulating the contained data. Multiple methods in C++ allow you to access vector elements with both speed and safety.
Random access
The subscript []
operator allows direct element access via indices, similar to arrays. In the following example, given a vector, the expression numbers[1]
returns the value 20
. However, using this operator doesn’t involve boundary checks. An index that is out of range, such as numbers[10]
, results in undefined behavior, leading to unpredictable outcomes.
This is shown in the following example:
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {10, 20, 30, 40, 50}; const auto secondElement = numbers[1]; std::cout << "The second element is: " << secondElement ...