C++ Vector Insert: Add Element at Position
To add elements to a vector at a specific position, you can use the insert() function. Below is an example code:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 在第三个位置添加元素
vec.insert(vec.begin() + 2, 10);
for (int i : vec) {
std::cout << i << " ";
}
return 0;
}
In the above example, we used the insert() function to add the element 10 at the third position (index 2) to the vector vec. The final output is: 1 2 10 3 4 5.