Accessing Vector Elements
In the previous exercise, we learned how to create a vector. Now we'll see how to access individual elements of a vector.
Each element in a vector has its index, which is its position in the vector. Indexes start from zero. This means that the first element has index 0, the second element has index 1, and so on.
Let's look at an example:
std::vector newYearResolutions = {"Write a diary", "Take a falconry course", "Learn to juggle"};
In this example, "Write a diary"
is at index 0, "Take a falconry course"
is at index 1, "Learn to juggle"
is at index 2.
If we want to access the first element in the vector newYearResolutions
and print it, we use square brackets with the index of the element we want to access. For example:
std::cout << newYearResolutions[0] << std::endl;
// Prints: Write a diary
Similarly, we can access other elements in the vector and print them:
std::cout << newYearResolutions[1] << std::endl; // Prints: Take a falconry course
std::cout << newYearResolutions[2] << std::endl; // Prints: Learn to juggle
Or we can store the value in a variable:
std::string firstResolution = newYearResolutions[0];
Instructions
Store one colleague from the vector colleagues
into a variable named favoriteColleague
.
Print the value of the variable favoriteColleague
.
Start programming for free
4/10