How to modify a specific element in a vector?
To modify an element at a specific position in a vector, you can use the index operator [] to access and modify that element. Here is an example code for modifying an element at a specified position in a vector:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 修改第三个元素(索引为2)
vec[2] = 10;
// 输出修改后的 vector
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
The output is: 1 2 10 4 5.
In the example above, we accessed and modified the element at index 2 in the vector using vec[2], changing it to 10. Finally, we output the elements in the modified vector.
Additionally, you can also access and modify the last element in the vector by using vec.back(). For example, vec.back() = 20; will change the last element to 20.