C++ 列表庫 - insert() 函式



描述

C++ 函式std::list::insert() 透過在容器中插入新元素來擴充套件列表。此成員函式會增加列表的大小。

宣告

以下是來自 `std::list` 標頭檔案的 `std::list::insert()` 函式的宣告。

C++98

template <class InputIterator>
void insert (iterator position, InputIterator first, InputIterator last);

C++11

template <class InputIterator>
iterator insert (const_iterator position, InputIterator first, InputIterator last);

引數

  • position − 列表中要插入新元素的位置。

  • first − 範圍初始位置的輸入迭代器。

  • last − 範圍最終位置的輸入迭代器。

返回值

返回一個指向新插入元素的迭代器。

異常

如果重新分配失敗bad_alloc異常將被丟擲。

時間複雜度

線性,即 O(n)

示例

以下示例演示了 `std::list::insert()` 函式的用法。

#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l1 = {3, 4, 5};
   list<int> l2 = {1, 2};

   l1.insert(l1.begin(), l2.begin(), l2.end());

   cout << "List contains following elements" << endl;

   for (auto it = l1.begin(); it != l1.end(); ++it)
      cout << *it << endl;

   return 0;
}

讓我們編譯並執行上述程式,這將產生以下結果:

List contains following elements
1
2
3
4
5
list.htm
廣告
© . All rights reserved.