列表是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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。