C++ <list> insert function

C++ container class <list>


insertis used in list forInserts an element at a specified positionfunctions, and is the most flexible operation of linked lists.

insertIs a member function of the container class, used to insert one or more elements at a specified position in the linked list.

In the list,insertHas a time complexity of O(1), because only pointers need to be adjusted.

Word Definitions: insertMeans "insert," i.e., adding an element at a specified position.


Basic syntax and parameters

insertIs a member function of the container class, requiring the insertion position and element to be specified.

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&lt;class InputIt&gt;
void insert(iterator pos, InputIt first, InputIt last);

Parameter description

  • Parameter: pos- Iterator of the insertion position
  • Parameter: value- The value of the element to insert

Function description

  • Return Value: Returns an iterator pointing to the first inserted element.
  • Effect: Inserts an element at the specified position, and subsequent elements are shifted backward in order.

Example

Example 1: Basic usage - inserting a single element

Example

#include <iostream>
#include <list>

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 running result:

原始 list: 1 2 3 4 5
插入 100 后: 1 100 2 3 4 5

Example 2: Inserting multiple elements

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {1, 5};

    std::cout << "Original: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    // Insert 3 zeros in the middle
    auto it = numbers.begin();
    std::advance(it, 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 running result:

原始: 1 5
插入 3 个 0 后: 1 0 0 0 5

C++ container class <list>

other extensions