C++ insert function
insert is used in list toinserts an element at a specified positionfunction; it is the most flexible operation on a linked list.
insert is a member function of the container class, used to insert one or more elements at a specified position in the linked list.
In list,insert has a time complexity of O(1), because only pointers need to be adjusted.
Word meaning: insert means "insert," i.e., to add elements at a specified position.
Basic syntax and parameters
insert is a member function of the container class that requires specifying the insertion position and the element.
Syntax format
iterator insert(iterator pos, const T& value);
iterator insert(iterator pos, T&& value);
void insert(iterator pos, size_type count, const T& value);
template
void insert(iterator pos, InputIt first, InputIt last);
Parameter Description
- Parameters:
pos- Iterator for the insertion position - Parameters:
value- The element value to insert
Function description
- Return Value: Returns an iterator pointing to the first inserted element.
- effect: Inserts an element at the specified position; subsequent elements are shifted back in order.
Example
Example 1: Basic usage - insert a single element
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
1
,
2
,
3
,
4
,
5
};
std
::
cout
<<
"Original list: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
endl
;
// Insert 100 at the second position (iterator)
auto
it
=
std
::
next
(
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:
原始 list: 1 2 3 4 5
插入 100 后: 1 100 2 3 4 5
Example 2: Insert multiple elements
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
1
,
5
};
std
::
cout
<<
"Original: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
// Insert three 0s in the middle
auto
it
=
numbers.
begin
(
)
;
std
::
advance
(
it,
1
)
;
numbers.
insert
(
it,
3
,
0
)
;
std
::
cout
<<
"After inserting three 0s: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
原始: 1 5
插入 3 个 0 后: 1 0 0 0 5
The C++ container class