C++ <list> insert 関数

C++ 容器类 <list>C++ コンテナクラス <list>


insertlist において、指定位置に要素を挿入する関数であり、リンクリストで最も柔軟な操作です。

insertコンテナクラスのメンバ関数で、リンクリストの指定位置に1つ以上の要素を挿入するために使用します。

list では、insertの時間計算量はO(1)です。ポインタを調整するだけで済むからです。

単語の意味: insert「挿入」を意味し、指定位置に要素を追加することです。


基本構文とパラメータ

insertコンテナクラスのメンバ関数で、挿入位置と要素を指定する必要があります。

構文形式

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);

パラメータの説明

  • パラメータ: pos- 挿入位置のイテレータ
  • パラメータ: value- 挿入する要素の値

関数の説明

  • 戻り値: 挿入された最初の要素を指すイテレータを返します。
  • 効果: 指定位置に要素を挿入し、後続の要素は順に後方へ移動します。

例

例1:基本的な使い方 - 単一要素の挿入

例

#include <iostream>
#include <list>

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

    std::cout << "元の list: ";
    for(int n : numbers) std::cout << n << " ";
    std::endl;

    // 2番目の位置(イテレータ)に100を挿入
    auto it = std::next(numbers.begin(), 1);
    numbers.insert(it, 100);

    std::cout << "100を挿入後: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

実行結果の予想:

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

例2:複数の要素を挿入

例

#include <iostream>
#include <list>

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

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

    // 中央に0を3つ挿入
    auto it = numbers.begin();
    std::advance(it, 1);
    numbers.insert(it, 3, 0);

    std::cout << "0を3つ挿入後: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

実行結果の予想:

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

C++ 容器类 <list>C++ コンテナクラス <list>

その他の拡張