Accessing Elements
Part of the Logic & Flow section of Coddy's C++ journey — lesson 12 of 56.
Now that you can create vectors and add elements to them, you need to know how to retrieve specific elements from your vector. C++ provides two main ways to access individual elements: the square bracket operator and the .at() method.
The square bracket operator [] works just like with regular arrays. You specify the index of the element you want to access:
std::vector<int> numbers = {10, 20, 30, 40};
int first = numbers[0]; // Gets 10
int third = numbers[2]; // Gets 30The .at() method provides an alternative way to access elements with an important difference - it includes bounds-checking:
int first = numbers.at(0); // Gets 10
int third = numbers.at(2); // Gets 30The key difference is safety: if you try to access an index that doesn't exist, [] can cause unpredictable behavior, while .at() will throw an exception to alert you of the error. For learning purposes, both methods work well, but .at() provides extra protection against accessing invalid positions in your vector.
Challenge
EasyCreate a program that demonstrates vector element access by retrieving specific elements from a vector using both the square bracket operator and the .at() method.
The following inputs will be provided:
- An integer
nrepresenting the number of elements in the vector - Then
nintegers to populate the vector - An integer
index1representing the first index to access - An integer
index2representing the second index to access
Your program should:
- Create a
std::vector<int>nameddata - Use
push_back()to add each of theninput numbers to the vector - Access the element at
index1using the square bracket[]operator and store it in a variable namedvalue1 - Access the element at
index2using the.at()method and store it in a variable namedvalue2 - Print the accessed values and their corresponding indices
- Print the first and last elements of the vector using index-based access
Use the following exact output format:
Element at index [index1]: [value1]
Element at index [index2]: [value2]
First element: [first value]
Last element: [last value]For accessing the last element, use data.size() - 1 as the index with the square bracket operator.
Cheat sheet
C++ vectors provide two main ways to access individual elements:
Square bracket operator []:
std::vector<int> numbers = {10, 20, 30, 40};
int first = numbers[0]; // Gets 10
int third = numbers[2]; // Gets 30The .at() method:
int first = numbers.at(0); // Gets 10
int third = numbers.at(2); // Gets 30The key difference is safety: [] can cause unpredictable behavior if accessing invalid indices, while .at() throws an exception for bounds-checking protection.
To access the last element, use data.size() - 1 as the index.
Try it yourself
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Read input
int n;
cin >> n;
vector<int> data;
// Read n integers and add them to the vector
for (int i = 0; i < n; i++) {
int num;
cin >> num;
data.push_back(num);
}
int index1, index2;
cin >> index1;
cin >> index2;
// TODO: Write your code below
// Access elements using [] operator and .at() method
// Store the accessed values in value1 and value2
// Output the results
cout << "Element at index " << index1 << ": " << value1 << endl;
cout << "Element at index " << index2 << ": " << value2 << endl;
cout << "First element: " << /* access first element */ << endl;
cout << "Last element: " << /* access last element using data.size() - 1 */ << endl;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items