Back To Course Outline
Back To Chapter Six

Creating a List & Accessing its Two Ends

There are three constructors for the class list:

There are some operations for class list: Example:
1. Create an empty list first, add items into list by push_back or push_front functions.
#include <iostream>
#include <list>

using namespace std;

void main()
{
 list<int> Scores;      //Call the constructor list();

 Scores.push_front(5);
 Scores.push_front(10);
 cout<<Scores.front()<<endl;
 cout<<Scores.back()<<endl;
 Scores.push_back(15);
 cout<<Scores.front()<<endl;
 cout<<Scores.back()<<endl;
}



#include <iostream>
#include <list>
#include <string>

using namespace std;

void main()
{
 list<string> Names;
 string Temp;

 for(int i=0; i<4; i++)
 {
     cout<<"Enter a name: ";
     cin>>Temp;
     Names.push_back(Temp);
     cout<<Names.front()<<endl;
     cout<<Names.back()<<endl;
 }
}



2.  Using the address range [first, last), create a list.
#include <iostream>
#include <list>
#include <string>

using namespace std;

void main()
{
 string Temp[]={"Tim","Austin","William"};
 list<string> Names(Temp,Temp+3);

 for(int i=0; i<3; i++)
 {
     cout<<"The "<<i+1<<"th front and back:"<<endl;
     cout<<Names.front()<<endl;
     cout<<Names.back()<<endl;
     Names.pop_front();
 }
}



3. Create a list with n elements, each having a specified value.
#include <iostream>
#include <list>

using namespace std;

void main()
{
 list<double> DayIncome(5,21.5);

    for(int i=0; i<5; i++)
 {
     cout<<DayIncome.front()<<endl;
  DayIncome.pop_front();
 }

 list<int> Scores(5);
    for(int j=0; j<5; j++)
 {
     cout<<Scores.front()<<endl;
  Scores.pop_front();
 }

}