C++ List: How to Add, Assign, Delete List in C++

0
6422
C++ List Tutorial With Example | List in C++ Standard Template Library (STL)

The list uses non-contiguous memory allocation, so traversal is slower than vector in C++. The list allows insertion and deletion operation anywhere within a sequence in constant time.

C++ List

C++ List is a built-in sequence container with STL(Standard Template Library) that allows non-contiguous memory allocation. However, the list doesn’t provide fast random access and only supports sequential access in both directions.

C++ Lists can shrink or expand from both ends at run time. The storage requirement is fulfilled automatically by the internal allocator. By default, the list is doubly linked. Since it is a doubly-linked list, the insertion and deletion are fast on the list.

Elements of the list can be scattered in different chunks of memory. The container stores the necessary information to allow sequential access to its data.

Zero-sized lists are also valid. In that case list.begin() and list.end() points to the same location. But the behavior of calling front() or back() is undefined.

Syntax

The definition of the list from its header file is as follows.

template < class T, class Alloc = allocator<T> > class list;

Parameters

  1. T − Type of the element contained.

    T may be substituted by any other data type, including a user-defined type.

  2. Alloc − Type of allocator object.

    The allocator class template is used by default, which defines the simplest memory allocation model and is value-independent.

If we want to make a list of integers, we can make it by the following code.

list<int> integer_list;

Member types in C++ List

Member functions can use the following member types as parameters or return types.

Sr.No. Member types Definition
1 value_type T (First parameter of the template)
2 allocator_type Alloc (Second parameter of the template)
3 reference value_type&
4 const_reference const value_type&
5 pointer value_type*
6 const_pointer const value_type*
7 iterator the random-access iterator to value_type
8 const_iterator the random-access iterator to const value_type
9 reverse_iterator std::reverse_iterator <iterator>
10 const_reverse_iterator std::reverse_iterator <const_iterator>
11 size_type size_t
12 difference_type ptrdiff_t

List Constructors

See the following constructors in the C++ list.

(1) empty container constructor (default constructor)
 constructs an empty container with no elements.
 (2) fill constructor
It constructs a container with n elements. Each element is a copy of val.
 (3) range constructor
It constructs a container with as many elements as the range [first, last), with each element constructed from its corresponding element in that range in the same order.
 (4) copy constructor
It constructs a container with a copy of each element in x, in the same order.

Destructor

The C++ destructor std::list::~list() destroys list object by deallocating it’s memory.

You can define the c++ destructor using the following code.

~list();

Functions used with List in C++

push_back()

They are used for adding a new element at the end of a list. For example, suppose the list is L, and we want to insert an element at its end. It can be done like this.

L.push_back(element);

push_front()

They are used for adding a new element at the start of a list. For example, suppose the list is L, and we want to insert an element at its front. It can be done like this.

L.push_front(element);

pop_back()

They are used for removing an element from the end of the list. Reduces the size of the list by one. For example, suppose the list is L. It can be done like this.

L.pop_back();

pop_front()

They are used for removing an element from the start of the list. Reduces the size of the list by one. For example, suppose the list is L.

L.pop_front();

front()

 It returns the first element from the list. So if we want to check the value of the first element of the list, it can be used.

L.front();

back()

It returns the last element from the list. So if we want to check the value of the last element of the list, it can be used.

L.back();

empty()

It returns one if the list is empty. Otherwise, it returns 0.

L.empty();

insert()

It is used to insert the elements at any position of the list. It takes three parameters to position, several elements to insert, and a value to insert. By default, the number of elements is set to 1.

L.insert(iterator, num_of_elements, element);

erase()

It is used to erase one element or a range of elements from the list. Just an integer position is passed to delete one element, which will be deleted. To delete a range, starting iterator and an ending iterator must be given.

L.erase(list_iterator); // to delete one element

L.erase(start_iterator, last_iterator); // for range

assign()

It is used to assign new elements to the list by replacing current elements and resizing the list. Two parameters number of values to be assigned and the second is the value to be assigned.

L.assign(number of times, value);

remove()

It takes a value as a parameter and removes all the elements having this value from the list.

L.remove(value);

reverse()

As the name says, it reverses the order of elements in the list.

L.reverse();

size()

It returns the number of elements present in the list.

L.size();

begin()

It returns the iterator to the first element in the list.

List <data_type>::iterator = L.begin();

end()

It returns the iterator pointing to the theoretical last element, which follows the last element.

L.end();

sort()

It is used to sort the elements of a list in increasing order.

L.sort();

clear()

It is used to remove all the elements of the list container. So the size of the list becomes 0.

L.clear();

Let’s see the following example code.

// list.cpp

#include <iostream>
#include <bits/stdc++.h>
using namespace std;


void showTheContent(list<int> l)
{
     list<int>::iterator it;
      for(it=l.begin();it!=l.end();it++)
   {
       cout <<  *it << " ";
   }
   cout << "\n";
}
int main()
{
   // Sample Code to show List and its functions

   list<int> list1,list2;
   int i;
   // inserting at the back
   for(i=0;i<10;i++)
    list1.push_back(i+1);

   //inserting at the front
   for(i=0;i<10;i++)
    list2.push_front(i+1);

   cout << "Content of List 1: ";
   showTheContent(list1);
   cout << "Content of list 2: ";
   showTheContent(list2);

   // sorting the second list
   list2.sort();
   cout << "Sorted List2 : ";
   showTheContent(list2);

   //Removing five elements from front in list1.
   int times = 5;
   while(times--)
   {
       list1.pop_front();
   }
   cout << "Content of List 1: " ;
   showTheContent(list1);
   //Removing five elements from the back in list2.
   times=5;
   while(times--)
   {
       list2.pop_back();
   }
   cout << "Content of List 2: ";
   showTheContent(list2);

    //seek the first element of list 1
    cout << list1.front() << " is now at the front in list 1\n";
    // seek the last element in list 2
    cout << list2.back() << " is now the last element in list 2\n";

    //Inserting elements in list 1.
    list1.insert(list1.begin(),5,10);
    cout << "After Insertion list 1: ";
    showTheContent(list1);

    //remove() to remove all the elements with value 10.
    list1.remove(10);
    cout << "After Removal list 1: ";
    showTheContent(list1);

    // size() to know the number of elements
    cout << "No. of elements in list 1: ";
    cout << list1.size() << "\n";

    //Reversing the content of list 2
    list2.reverse();
    cout << "Reversed list 2: ";
    showTheContent(list2);

    //erasing first element of list 2
    list2.erase(list2.begin());
    cout << "After erasing from list 2: ";
    showTheContent(list2);

    //Removing all elements from list 1.
    list1.clear();
    // Use of empty() function
    if(list1.empty()) cout << "List 1 is now empty\n";
    else cout << "Not Empty\n";

    // use of assign function
    list1.assign(5,2); // 2 2 2 2 2
    cout << "List 1: ";
    showTheContent(list1);


    return 0;
}

See the following output.

C++ List Tutorial With Example

That’s it for this tutorial.

Recommended Posts

C++ Set

C++ Vector

Pair in C++

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.