C++ STL 中的 list insert()


本任务演示 C++ STL 中 list insert() 函数的功能。

什么是 STL 中的 List

List 是一种容器,允许在序列中的任何位置进行常数时间插入和删除操作。List 以双向链表的形式实现。List 允许非连续内存分配。与数组、向量和双端队列相比,List 在容器的任何位置执行元素的插入、提取和移动操作的效率更高。在 List 中,对元素的直接访问速度较慢,并且 List 与 forward_list 类似,但 forward list 对象是单向链表,只能向前迭代。

什么是 insert()

list insert() 函数用于在列表中插入元素。

  • 该函数用于在指定位置插入元素。

  • 该函数还用于在列表中插入 n 个元素。

  • 它还用于在指定位置插入指定范围内的元素。

语法

insert(iterator position, const value_type& val)
insert(iterator position, size_type n, const value_type& value)
insert(iterator position, iterator first, iterator last)

参数

Val - 指定要插入列表中的新元素。

Position - 指定在容器中插入新元素的位置。

n - 要插入的元素数量。

First, last - 指定迭代器,用于指定要插入的元素范围。

返回值

它返回一个迭代器,指向第一个新插入的元素。

示例

输入 列表 - 50 60 80 90

输出 新列表 - 50 60 70 80 90

输入 列表 - T R E N D

输出 新列表 - T R E N D S

可遵循的方法      

  • 首先,我们声明列表
  • 然后我们打印列表。

  • 然后我们声明 insert() 函数。

使用上述方法,我们可以在列表中插入新元素。新元素应与列表具有相同的数据类型。

示例

/ / C++ code to demonstrate the working of list insert( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   List<int> list = { 55, 84, 38, 66, 67 };
   / / print the deque
   cout<< “ List: “;
   for( auto x = List.begin( ); x != List.end( ); ++x)
      cout<< *x << “ “;
   / / declaring insert( ) function
   list.insert( x, 6);
   / / printing new list after inserting new element
   cout<< “New list “;
   for( x=list.begin( ); x != list.end( ); ++x)
      cout<< “ “<<*x;
   return 0;
}

输出

如果我们运行以上代码,则会生成以下输出

Input - List: 55 84 38 66 67
Output - New List: 6 84 38 66 67

示例

/ / C++ code to demonstrate the working of list insert( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main( ){
   List<char> list ={ ‘F’, ‘B’, ‘U’, ‘A’, ‘R’, ‘Y’ };
   cout<< “ List: “;
   for( auto x = list.begin( ); x != list.end( ); ++x)
   cout<< *x << “ “;
   / / declaring insert( ) function
   list.insert(x + 1, 1, ‘E’);
   / / printing new list after inserting new element
   cout<< “ New List:”;
   for( auto x = list.begin( ); x != list.end( ); ++x)
   cout<< “ “ <<*x;
   return 0;
}

输出

如果我们运行以上代码,则会生成以下输出

Input – List: F B U A R Y
Output – New List: F E B U A R Y

示例

/ / C++ code to demonstrate the working of list insert( ) function in STL
#include<iostream.h>
#include<list.h>
#include<vector.h>
Using namespace std;
int main( ){
   list<int> list ={ 10, 44, 34, 98, 15 };
   cout<< “ list: “;
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<< *x << “ “;
   vector<int> l(2, 17);
   list.insert(x, l.begin( ), l.end( ) );
   / / printing new list after inserting new element
   cout<< “ New list:”;
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<< “ “ <<*x;
   return 0;
}

输出

如果我们运行以上代码,则会生成以下输出

Input – List: 10 44 34 98 15
Output – New list: 17 17 10 44 34 98 15

更新于: 2020年2月26日

9K+ 阅读量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.