列表是C++中用于以非连续方式存储数据的容器。通常,数组和向量本质上是连续的,因此,与列表中的插入和删除选项相比,插入和删除操作的成本更高。
清单::push_front()
push_front()函数用于将元素从前面推入列表。在当前第一个元素和容器大小增加1之前,将新值插入到列表的开头。
用法:
listname.push_front(value) 参数: The value to be added in the front is passed as the parameter Result: Adds the value mentioned as the parameter to the front of the list named as listname
例子:
Input:list list{1, 2, 3, 4, 5}; list.push_front(6); Output:6, 1, 2, 3, 4, 5 Input:list list{5, 4, 3, 2, 1}; list.push_front(6); Output:6, 5, 4, 3, 2, 1
错误和异常
- 强大的异常保证-如果引发异常,则容器中没有任何更改。
- 如果列表不支持作为参数传递的值,则它将显示未定义的行为。
// CPP program to illustrate
// push_front() function
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> mylist{ 1, 2, 3, 4, 5 };
mylist.push_front(6);
// list becomes 6, 1, 2, 3, 4, 5
for (auto it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
}
输出:
6 1 2 3 4 5
应用:使用push_front()函数输入具有以下编号和顺序的空列表,并对给定列表进行排序。
Input: 7, 89, 45, 6, 24, 58, 43 Output:6, 7, 24, 43, 45, 58, 89
// CPP program to illustrate
// application Of push_front() function
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> mylist{};
mylist.push_front(43);
mylist.push_front(58);
mylist.push_front(24);
mylist.push_front(6);
mylist.push_front(45);
mylist.push_front(89);
mylist.push_front(7);
// list becomes 7, 89, 45, 6, 24, 58, 43
// Sorting function
mylist.sort();
for (auto it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
}
输出:
6 7 24 43 45 58 89
清单::push_back()
push_back()函数用于将元素从背面推入列表。在当前最后一个元素和容器大小增加1之后,将新值插入到列表的末尾。
用法:
listname.push_back(value) 参数: The value to be added in the back is passed as the parameter Result: Adds the value mentioned as the parameter to the back of the list named as listname
例子:
Input:list list{1, 2, 3, 4, 5}; list.push_back(6); Output:1, 2, 3, 4, 5, 6 Input:list list{5, 4, 3, 2, 1}; list.push_front(0); Output:5, 4, 3, 2, 1, 0
错误和异常
- 强大的异常保证-如果引发异常,则容器中没有任何更改。
- 如果列表不支持作为参数传递的值,则它将显示未定义的行为。
// CPP program to illustrate
// push_back() function
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> mylist{ 1, 2, 3, 4, 5 };
mylist.push_back(6);
// list becomes 1, 2, 3, 4, 5, 6
for (auto it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
}
输出:
1 2 3 4 5 6
应用:使用push_back()函数输入具有以下编号和顺序的空列表,并对给定列表进行排序。
Input: 7, 89, 45, 6, 24, 58, 43 Output:6, 7, 24, 43, 45, 58, 89
// CPP program to illustrate
// application Of push_back() function
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> mylist{};
mylist.push_back(7);
mylist.push_back(89);
mylist.push_back(45);
mylist.push_back(6);
mylist.push_back(24);
mylist.push_back(58);
mylist.push_back(43);
// list becomes 7, 89, 45, 6, 24, 58, 43
// Sorting function
mylist.sort();
for (auto it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
}
输出:
6 7 24 43 45 58 89
相关用法
注:本文由纯净天空筛选整理自AyushSaxena大神的英文原创作品 list::push_front() and list::push_back() in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。