Cpp Libs Vector Insert
[ C++ Container Class ](#)
* * *
`insert` is a function in vector used to **insert elements at a specified position**, and it is the most flexible insertion method among containers.
`insert` is a member function of container classes, used to **insert one or more elements at a specified position in the container**. It accepts an iterator position and the element(s) to be inserted.
`insert` provides the ability to insert elements at any position. Although it is less efficient than `push_back` in vector (as it requires moving subsequent elements), it offers more powerful functionality.
**Word Definition**: `insert` means "to insert", which adds elements at a specified location.
* * *
## Basic Syntax and Parameters
`insert` is a member function of container classes that requires specifying the insertion position and the element(s).
### Syntax Format
// Insert a copy of value at position pos iterator insert(iterator pos, const T& value);// Insert a copy of value at position pos (move) iterator insert(iterator pos, T&& value);// Insert n copies of value at position pos void insert(iterator pos, size_type n, const T& value);// Insert elements within the range [first, last) at position pos template void insert(iterator pos, InputIt first, InputIt last);// Insert using initializer list void insert(iterator pos, std::initializer_list ilist);
### Parameter Description
* **Parameter**: `pos`
* Type: Iterator (`iterator`)
* Description: Iterator pointing to the insertion position. The new element will be inserted before `pos`.
* **Parameter**: `value`
* Type: Same as container element type
* Description: Value of the element to be inserted.
* **Parameter**: `n`
* Type: `size_type`
* Description: Number of elements to be inserted.
### Function Description
* **Return Value**: Returns an iterator pointing to the first inserted element (for single-element insertion).
* **Effect**: Inserts elements at the specified position, shifting subsequent elements forward.
* **Note**: `insert` may cause memory reallocation, invalidating all existing iterators.
* * *
## Examples
Let's explore a series of examples to fully master the usage of `insert`.
### Example 1: Basic Usage - Inserting a Single Element
## Example
#include
#include
int main(){
std::vector numbers ={1, 2, 3, 4, 5};
std::cout<<"Original vector: ";
for(int n : numbers) std::cout<< n <<" ";
std::cout<< std::endl;
// Insert 100 at the second position (index 1)
auto it = numbers.begin()+1;
numbers.insert(it, 100);
std::cout<<"After inserting 100: ";
for(int n : numbers) std::cout<< n <<" ";
std::cout<< std::endl;
return 0;
}
**Expected Output:**
Original vector: 1 2 3 4 5 After inserting 100: 1 100 2 3 4 5
**Code Explanation:**
1. `numbers.begin() + 1` points to the position of the second element.
2. `insert` inserts 100 before that position.
3. All subsequent elements shift one position to the right.
### Example 2: Inserting Elements at the Beginning
Using `begin()` allows inserting elements at the beginning of the container.
## Example
#include
#include
#include
int main(){
std::vector names ={"Bob", "Charlie"};
std::cout<<"Original: ";
for(const auto& n : names) std::cout<< n <<" ";
std::cout<< std::endl;
// Insert at the beginning
names.insert(names.begin(), "Alice");
std::cout<<"Inserting Alice at the beginning: ";
for(const auto& n : names) std::cout<< n <<" ";
std::cout<< std::endl;
return 0;
}
**Expected Output:**
Original: Bob Charlie Inserting Alice at the beginning: Alice Bob Charlie
**Code Explanation:**
* `names.begin()` points to the first element.
* Inserting at that position makes the new element the first one.
### Example 3: Inserting Multiple Identical Elements
Multiple identical elements can be inserted at a specified position.
## Example
#include
#include
int main(){
std::vector numbers ={1, 5};
std::cout<<"Original: ";
for(int n : numbers) std::cout<< n <<" ";
std::endl;
// Insert 3 zeros in the middle
auto it = numbers.begin()+1;
numbers.insert(it, 3, 0);
std::cout<<"After inserting 3 zeros: ";
for(int n : numbers) std::cout<< n <<" ";
std::cout<< std::endl;
return 0;
}
**Expected Output:**
Original: 1 5 After inserting 3 zeros: 1 0 0 0 5
**Code Explanation:**
* `insert(it, 3, 0)` inserts 3 elements with value 0 before position it.
### Example 4: Inserting Elements from Another Vector
Multiple elements can be inserted from another container.
## Example
#include
#include
int main(){
std::vector v1 ={1, 2, 3};
std::vector v2 ={10, 20, 30};
std::cout<<"v1: ";
for(int n : v1) std::cout<< n <<" ";
std::cout<< std::endl;
std::cout<<"v2: ";
for(int n : v2) std::cout<< n <<" ";
std::cout<< std::endl;
// Insert all elements of v2 into v1 at the second position
v1.insert(v1.begin()+1, v2.begin(), v2.end());
std::cout<<"After insertion in v1: ";
for(int n : v1) std::cout<< n <<" ";
std::cout<< std::endl;
return 0;
}
**Expected Output:**
v1: 1 2 3 v2: 10 20 30 After insertion in v1: 1 10 20 30 2 3
**Code Explanation:**
* `v1.insert(v1.begin() + 1, v2.begin(), v2.end())` inserts all elements of v2 before the second position in v1.
### Example 5: Inserting Using Initializer Lists
C++11 supports inserting elements using initializer lists.
## Example
#include
#include
int main(){
std::vector numbers ={1, 5};
std::cout<<"Original: ";
for(int n : numbers) std::cout<< n <<" ";
std::cout<< std::endl;
// Insert using initializer list
numbers.insert(numbers.begin()+1, {2, 3, 4});
std::cout<<"After insertion: ";
for(int n : numbers) std::cout<< n <<" ";
std::cout<< std::endl;
return 0;
}
**Expected Output:**
Original: 1 5 After insertion: 1 2 3 4 5
**Code Explanation:**
* Using `initializer_list` allows inserting multiple elements at once.
### Example 6: Efficiency Issues with insert
Using `insert` in a vector to insert elements at the beginning or middle is inefficient.
## Example
#include
#include
#include
int main(){
const int N =10000;
// Inserting at the beginning (inefficient)
std::vector v1;
auto start1 = std::chrono::high_resolution_clock::now();
for(int i =0; i < N;++i){
v1.insert(v1.begin(), i);
}
auto end1 = std::chrono::high_resolution_clock::now();
auto duration1 = std::chrono::duration_cast(end1 - start1);
// Inserting at the end (efficient)
std::vector v2;
v2.reserve(N);
auto start2 = std::chrono::high_resolution_clock::now();
for(int i =0; i < N;++i){
v2.push_back(i);
}
auto end2 = std::chrono::high_resolution_clock::now();
auto duration2 = std::chrono::duration_cast(end2 - start2);
std::cout<<"Time taken to insert "<< N <<" elements at the beginning: "<< duration1.count()<<" microseconds"<< std::endl;
std::cout<<"Time taken to insert "<< N <<" elements at the end: "<< duration2.count()<<" microseconds"<< std::endl;
return 0;
}
**Code Explanation:**
* Inserting elements at the beginning of a vector requires shifting all existing elements, making it very inefficient.
* If frequent insertions at the beginning are needed, consider using `deque` or `list`.
* Prefer `push_back` for adding elements at the end.
* * C++ Container Class ](#)
YouTip