C++ STL 中的 push_front() 函数
在本文中,我们将讨论 C++ 中 push_front() 函数的工作原理、语法和示例。
什么是 STL 中的列表
列表是一种数据结构,它允许在序列中的任何位置进行常数时间插入和删除。列表以双向链表的形式实现。列表允许非连续内存分配。与数组、向量和双端队列相比,列表在容器的任何位置执行元素的插入、提取和移动方面表现更好。在列表中,对元素的直接访问速度很慢,并且列表类似于 forward_list,但 forward_list 对象是单向链表,它们只能向前迭代。
什么是 push_front()
push_front() 是 C++ STL 中的一个内置函数,它在头文件中声明。push_front() 用于将元素推入(插入)到列表容器的开头。如果容器为空,则将其推入第一个位置,并且该元素成为第一个元素;如果容器事先包含元素,则该函数将其传递的元素推入前面,而先前位于第一个位置的元素将成为第二个元素。此函数将容器的大小增加 1。
语法
void push_front (const value_type& element1); void push_front (value_type&& element1); This function accepts only 1 element which is to be pushed/inserted.
返回值
此函数不返回任何内容。
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
//create a list
list myList;
//insert elements
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);
myList.push_back(4);
//List before applying push_front()
cout<<"List : ";
for (auto i = myList.begin(); i!= myList.end(); i++)
cout << *i << " ";
//calling push_front()
myList.push_front(0);
cout<<"\nList after calling push_front() : ";
for (auto i = myList.begin(); i!= myList.end(); i++)
cout << *i << " ";
return 0;
}
输出
如果我们运行上述代码,它将生成以下输出
List : 1 2 3 4 List after calling push_front(): 4 3 2 1
示例
#include <iostream>
#include <list>
int main (){
//adding two integer values with the value 30
std::list<int> myList (2,30);
myList.push_front (20);
myList.push_front (10);
std::cout<<"elements in my list are : ";
for (std::list<int>::iterator i = myList.begin(); i!= myList.end(); ++i)
std::cout << ' ' << *i;
std::cout << '\n';
return 0;
}输出
如果我们运行上述代码,它将生成以下输出
Elements in my list are : 10 20 30 30
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP