How to change the value of a specific element in a vector container?

To modify the value of an element in a vector container, you can change the value by accessing it through either an index or an iterator.

  1. Accessing by index:
std::vector<int> vec = {1, 2, 3, 4, 5};
vec[2] = 10;  // 将第三个元素修改为10
  1. Accessing using an iterator:
std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int>::iterator it = vec.begin();
std::advance(it, 2);  // 移动迭代器到第三个元素
*it = 10;  // 将第三个元素修改为10

Both accessing elements by index and by iterator allow for modifying the values of elements within a vector container through assignment.

bannerAds