C++ STL 中的 list::emplace_front() 和 list::emplace_back()
在本文中,我们将讨论 C++ STL 中 list::emplace_front() 和 list::emplace_back() 函数的工作原理、语法和示例。
什么是 STL 中的列表?
列表是一种数据结构,允许在序列中的任何位置进行常数时间的插入和删除操作。列表实现为双向链表。列表允许非连续的内存分配。与数组、向量和双端队列相比,列表在容器中任何位置进行元素的插入、提取和移动操作的性能更好。在列表中,直接访问元素的速度较慢,列表类似于 forward_list,但 forward_list 对象是单向链表,只能向前迭代。
什么是 list::emplace_front()?
list::emplace_front() 是 C++ STL 中的一个内置函数,它在 <list> 头文件中声明。emplace_front() 用于在列表容器的开头放置(插入)元素。如果容器为空,它会在第一个位置推送元素,该元素成为第一个元素;如果容器事先包含元素,则该函数会将传递给它的元素插入到前面,而现有位于第一个位置的元素将成为第二个元素。此函数使容器的大小增加 1。
语法
listname.emplace_front (const value_type& element1); listname.emplace_front (value_type&& element1);
参数
此函数只接受一个要放置/插入的元素。
返回值
此函数不返回任何值。
示例
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()?
list::emplace_back() 是 C++ STL 中的一个内置函数,它在 <list> 头文件中声明。emplace_back() 用于在列表容器的末尾放置(插入)元素。如果容器为空,它只是简单地插入元素,容器的大小变为 1;如果容器事先包含元素,则该函数会将传递给它的元素插入到列表容器的末尾。此函数使容器的大小增加 1。
语法
listname.emplace_back(const value_type& element1); listname.emplace_back(value_type&& element1);
参数
此函数只接受一个要放置/插入的元素。
返回值
此函数不返回任何值。
示例
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP