Changing Elements
You can also change an element of a vector. Write the vector's name and the index in square brackets, just like when you read an element, and assign a new value with =, as you would to a variable:
std::vector<std::string> resolutions = {"Write a diary", "Take a falconry course", "Learn to juggle"};
resolutions[1] = "Take a painting course";
std::cout << resolutions[0] << ", " << resolutions[1] << ", " << resolutions[2] << std::endl;This prints:
Write a diary, Take a painting course, Learn to juggleThe element at index 1 now has a new value, and the old one is gone. Nothing was inserted or moved: the vector still has three elements, and the others stayed the same.
Make sure you don't write == instead of =. The statement resolutions[1] == "Take a painting course"; only compares the values and changes nothing. The program doesn't report any error, the vector just stays the same.
An element of a vector behaves like a variable of its type. So you can calculate with the elements of a vector of numbers, and +=, -= and ++ work too:
std::vector<int> points = {12, 7, 30};
points[1] += 5;
points[2]++;
std::cout << points[0] + points[1] << std::endl;
std::cout << points[1] << " " << points[2] << std::endl;This prints:
24
12 31points[1] += 5; added five to the second element, and points[2]++; increased the third element by one.
Instructions
- 1
Adam has moved to another team, and Daniel has taken his place. Below the output line, write a statement that changes the second element of
colleaguesto"Daniel". - 2
Then print the vector again in the same way, for example by copying the output line. Now the output shows the vector before and after the change:
Peter, Adam, Lucy Peter, Daniel, Lucy