C++ STL list, pop_back(), pop_front(), push_back() and push_front() code example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the C++ pop_back() to delete the element at the end of a list, pop_front() to delete the element at the beginning of a list, push_back() to add an element to the end of a list and push_front() to add an element to the beginning of a list in C++ programming
To show: How to use the C++ pop_back() to delete the element at the end of a list, pop_front() to delete the element at the beginning of a list, push_back() to add an element to the end of a list and push_front() to add an element to the beginning of a list in C++ programming
// C++ STL list, pop_back(), pop_front(), push_back() and push_front()
#include <list>
#include <iostream>
using namespace std;
int main(void)
{
// list containers
list <int> c1, c2, c3, c4;
// push/insert data
c1.push_back(1);
c1.push_back(2);
// print the data and do some operations
cout<<"The first element is, c1.front(): "<<c1.front()<<endl;
cout<<"The last element is, c1.back(): "<<c1.back()<<endl;
c1.pop_back( );
cout<<"After deleting the element at the end of the list, the last element is, c1.back(): "<<c1.back()<<endl;
c2.push_back(3);
c2.push_back(4);
cout<<"\nThe first element is, c2.front(): "<<c2.front()<<endl;
cout<<"The second element is, c2.back(): "<<c2.back()<<endl;
c2.pop_front( );
cout<<"After deleting the element at the beginning of the list, the first element is, c2.front(): "<<c2.front()<<endl;
c3.push_back(5);
if (c3.size() != 0)
cout<<"\nc3.push_back(5) - The last element, c3.back(): "<<c3.back()<<endl;
c3.push_back(6);
if (c3.size() != 0)
cout<<"c3.push_back(6) - The new last element, c3.back(): "<<c3.back()<<endl;
c4.push_front(7);
if (c4.size() != 0)
cout<<"\nc4.push_front(7) - The first element, c4.front(): "<<c4.front()<<endl;
c4.push_front(8);
if (c4.size() != 0)
cout<<"c4.push_front(8) - The new first element, c4.front(): "<<c4.front()<<endl;
return 0;
}
Output examples:
The first element is, c1.front(): 1
The last element is, c1.back(): 2
After deleting the element at the end of the list, the last element is, c1.back(): 1
The first element is, c2.front(): 3
The second element is, c2.back(): 4
After deleting the element at the beginning of the list, the first element is, c2.front(): 4
c3.push_back(5) - The last element, c3.back(): 5
c3.push_back(6) - The new last element, c3.back(): 6
c4.push_front(7) - The first element, c4.front(): 7
c4.push_front(8) - The new first element, c4.front(): 8
Press any key to continue . . .