列表的 push_back() 函数在 C++ STL 中


在本文中,我们将讨论 C++ 中 list:: push_back() 函数的工作原理、语法和示例。

STL 中的列表是什么

列表是一种数据结构,允许在序列中的任何位置进行恒定时间插入和删除。列表实现为双向链表。列表允许非连续内存分配。列表比数组、向量和队列更佳地执行容器中任何位置的元素的插入、提取和移动。列表中对元素的直接访问很慢,并且列表类似于 forward_list,但 forward_list 对象是单链表,且只能向前迭代。

list::push_back() 是什么

list::push_back() 是 C++ STL 中的内建函数,声明于头文件内。push_back() 用于在列表容器的末尾推送/插入元素。push_back 还将容器的尺寸增加 1。

语法

list_name. push_back (int ele);

该函数仅接受一个参数,即我们要推送/插入到 list_name 容器的末尾/最后位置的元素。

返回值

该函数不返回任何内容。它将仅在列表容器中插入该元素。

示例

 在线演示

#include<bits/stdc++.h>
using namespace std;
int main(){
   //create a list
   list<int> myList;
   //Displaying the initial size of a list
   cout<<"size of the list: "<<myList.size()<< endl;
   //inserting elements to the list
   myList.push_back(1);
   myList.push_back(2);
   myList.push_back(3);
   //Size of the list after inserting elements
   cout<<"Size of the list after inserting elements: "<<myList.size();
   return 0;
}

输出

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

Size of the list : 0
Size of the list after inserting elements: 3

更新于:26-2-2020

2K+ 查看次数

开启你的 职业 生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.