C++ STL中的forward_list insert_after()函数
forward_list::insert_after() 是一个内置函数,可让我们选择在前向链表中的给定迭代器指向的元素之后的位置插入元素。此函数的参数将被复制到所需位置。
语法:
forward_list_name.insert_after(iterator position, element)
或者,
forward_list_name.insert_after(iterator position, n, element)
或者,
forward_list_name.insert_after(iterator position, itr1, itr2)
或者,
forward_list_name.insert_after(iterator position, list)
参数: 根据不同的语法,函数接受不同的参数。让我们详细看一下上述每个语法的参数和工作方式。
- position, element: 参数 position 为迭代器类型,它指向要插入 element 值的位置之后。
- position, n, element: 参数 position 为迭代器类型,它指向要插入 element 值的位置之后。参数 n 指定要插入元素的次数。
- position, itr1, itr2: 参数 position 为迭代器类型,它指向要在其中插入值的位置之后。迭代器 itr1 和 itr2 表示范围 [itr1,itr2) 和此范围中的元素(包括 itr1 和排除 itr2 )将在指向给定位置的迭代器之后插入到前向链表中。
- position, list: 参数 position 为迭代器类型,它指向要插入值的位置之后。第二个参数 list 定义要插入到forward_list中的元素列表。
返回值: 此函数返回一个指向最后插入的元素的迭代器。下面的程序说明了上述函数:
// C++程序演示 // forward_list :: insert_after()函数 #include <forward_list> #include <iostream> #include <list> using namespace std; int main() { forward_list<int> fwlist = { 1, 2, 3, 4, 5 }; list<int> sampleList = { 8, 9, 10 }; //该迭代器指向第一个元素 auto it_new = fwlist.begin(); //要插入的新元素 int element = 20; /******************************/ /** 实现语法1 *****/ /******************************/ it_new = fwlist.insert_after(it_new,element); cout << "After Syntax 1:"; for(auto it = fwlist.cbegin(); it!= fwlist.cend(); it ++){ cout << * it <<“ ”; } // it_new指向插入的新元素,即20 //让它指向下一个元素 it_new ++; /******************************/ /** 实现语法2 *****/ /******************************/ it_new = fwlist.insert_after(it_new,3,element); cout << "\n\nAfter Syntax 2:"; for(auto it = fwlist.cbegin(); it!= fwlist.cend(); it ++){ cout << * it <<“ ”; } /******************************/ /** 实现语法3 *****/ /******************************/ it_new = fwlist.insert_after(it_new,sampleList.begin(), sampleList.end()); cout << "\n\nAfter Syntax 3:"; for(auto it = fwlist.cbegin(); it!= fwlist.cend(); it ++){ cout << * it <<“ ”; } /******************************/ /** 实现语法4 *****/ /******************************/ it_new = fwlist.insert_after(it_new,{50,60}); cout << "\n\nAfter Syntax 4:"; for(auto it = fwlist.cbegin(); it!= fwlist.cend(); it ++){ cout << * it <<“ ”; } return 0; }
输出:
After Syntax 1:1 20 2 3 4 5 After Syntax 2:1 20 2 20 20 20 3 4 5 After Syntax 3:1 20 2 20 20 20 8 9 10 3 4 5 After Syntax 4:1 20 2 20 20 20 8 9 10 50 60 3 4 5
时间复杂度: O(n)
辅助空间: O(1)
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com