C++ Vector Insert at Position: Guide
In C++, you can use the insert() function to add elements at a specific position in a vector. The first parameter of the insert() function is an iterator pointing to the position where the element is to be inserted, and the second parameter is the element to insert. Here is an example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 在第三个位置插入元素6
std::vector<int>::iterator it = vec.begin() + 2;
vec.insert(it, 6);
// 输出vector的内容
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
The output result is: 1 2 6 3 4 5.
In the example above, we first defined a vector with 5 elements. Then, we obtained an iterator it pointing to the third position using the begin() function and + operator. Next, we inserted element 6 at the position of it using the insert() function. Lastly, we used a for loop to iterate through the vector and output the value of each element.