Modifying Vector Elements
In the previous exercise, we learned how to access vector elements using their indexes. Now we'll see how to update the values of these elements.
Changing a vector element is simple. We use the same notation we used to access elements, and assign a new value using the =
operator, just like we would assign a value to a variable.
Let's look at an example:
std::vector newYearResolutions = {"Write a diary", "Take a falconry course", "Learn to juggle"};
Imagine we want to change the second resolution. We use the following code, where we insert a new element at index 1:
newYearResolutions[1] = "Take a painting course";
Now the vector newYearResolutions
will look like this:
{"Write a diary", "Take a painting course", "Learn to juggle"}
Instructions
Change the value of the second colleague (index 1) to "Daniel"
.
Start programming for free
5/10