在本文中,我们将讨论C ++ STL中list::emplace_front()和list::emplace_back()函数的工作原理,语法和示例。
列表是一种数据结构,允许按时间顺序在任意位置进行插入和删除。列表被实现为双向链接列表。列表允许非连续的内存分配。与数组,向量和双端队列相比,列表在容器中的任何位置执行元素的插入提取和移动效果都更好。在列表中,对元素的直接访问很慢,并且列表类似于forward_list,但是转发列表对象是单个链接列表,并且只能迭代转发。
list::emplace_front()是C ++ STL中的内置函数,在<list>头文件中声明。emplace_front()用于将元素插入(插入)在列表容器的开头。如果容器为空,则将元素推到第一个位置,并且该元素成为第一个元素;如果容器预先具有元素,则该函数将传递给它的元素插入到前面,并将位于第一个位置的现有元素插入将成为第二个要素。此功能将容器的大小增加1。
listname.emplace_front (const value_type& element1); listname.emplace_front (value_type&& element1);
此函数仅接受1要放置/插入的元素。
此函数不返回任何内容。
Input: list<int> mylist = {1, 2, 3, 4}; mylist.emplace_front(0) Output: List elements are = 0 1 2 3 4
#include <iostream> #include <list> using namespace std; int main(){ list<int> List; List.emplace_front(10); List.emplace_front(20); List.emplace_front(30); List.emplace_front(40); List.emplace_front(50); List.emplace_front(60); cout<<"Elements are : "; for(auto i = List.begin(); i!= List.end(); ++i) cout << ' ' << *i; return 0; }
输出结果
如果我们运行上面的代码,它将生成以下输出-
Elements are : 60 50 40 30 20 10
list::emplace_back()是C ++ STL中的内置函数,在<list>头文件中声明。emplace_back()用于将元素插入(插入)在列表容器的后面或结尾。如果容器为空,则只需插入元素,并且如果容器事先具有元素,则容器的大小将变为1,函数将在列表容器的末尾插入传递给它的元素。此功能将容器的大小增加1。
listname.emplace_back(const value_type& element1); listname.emplace_back(value_type&& element1);
此函数仅接受1要放置/插入的元素。
此函数不返回任何内容。
Input: list<int> list1 = {1, 2, 3, 4}; list1.emplace_back(5); Output: List: 1 2 3 4 5
#include <iostream> #include <list> using namespace std; int main(){ list<int> List; List.emplace_back(10); List.emplace_back(20); List.emplace_back(30); List.emplace_back(40); List.emplace_back(50); List.emplace_back(60); cout<<"elements are : "; for(auto i=List.begin(); i!= List.end(); ++i) cout << ' ' << *i; return 0; }
输出结果
如果我们运行上面的代码,它将生成以下输出-
Elements are : 10 20 30 40 50 60