Lists in Cpp

Lists of STL are  generic containers in C++.  They are implemented as doubly linked lists. Lists should be used instead of arrays as arrays are having many disadvantages, the most important one being the inability to grow in size.

Creation :

As list is a template class, you have to specify the type of elements such as int, float or some class name.

list lst;//creates an empty list 
lst.push_back(2);//adds an element at the back of list 
lst.push_front(5);//adds an element at the front of list 

Insertion
  You can add elements to the list using push_back and push_front methods.

Iteration
List elements can be accessed using iterators. Please note that you can not access the elements using [] operator of at() method.  

list::iterator it; 
for(it = lst.begin();it!=lst.end();it++) 
    cout<<*it<<" "; 


Here the iterator is starts from first element of the list and goes till the last element. If you want to travel backwords, you can use rbegin() and rend() methods of the iterator. Iterator can also be used to insert elements into the list.  

it2 = lst1.begin(); 
it2++; 
it2++; 
lst.insert(it2,10); 
lst.insert(it2,3,100);//now list is 5 2 10 100 100 100

Deletion

To remove elements from the list you can use clear, erase, pop_back and pop_front. clear empties the list, erase removes the element (or multiple elements) where iterator is pointing and pop_back removes last element and pop_front removes first element. remove removes the element(s) with a given value.

it2 = lst1.begin(); 
lst.erase(it2);//first erased. List is 2 10 100 100 100 
lst.remove(100);//100 are removed. List is 2 10 

Lists of objects

Don't be under the impression that, lists can be used only with pod (plain old data types) You can create a list of any class as shown below.
class Number {
int n; 
public: 
Number(int a=0):n(a){} 
int getN() {
return n;

void setN(int a)

n = a;

};
int main() 

list lst1; 
Number ob1,ob2(10);
lst1.push_back(ob1);
lst1.push_back(ob2);

Download the complete program from here

References : C++ Reference 
                   Yo Linux STL tutorial



Comments

Popular Posts