Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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 juggle

The 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 31

points[1] += 5; added five to the second element, and points[2]++; increased the third element by one.

Instructions

  1. 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 colleagues to "Daniel".

  2. 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
Back

3/10

  1. 1. Creating a Vector
  2. 2. Reading Elements
  3. 3. Changing Elements
  4. 4. Size and the Last Element
  5. 5. Index Out of Range
  6. 6. Adding Elements: push_back()
  7. 7. Removing Elements: pop_back()
  8. 8. Nested Vectors
  9. 9. Characters of a Text
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.