List Class in STL in C++

List class supports a bidirectional linear list.
Vector supports random access but a list can be accessed sequentially only. 
List can be accessed front to back or back to front.

What are lists in C++

1. A list is a contiguous container in C++.

2. It stores its elements in contiguous memory.

3. Lists are bidirectional which supports easy insertion and deletion of elements in it.

4. List access all its elements sequentially so list traversal is slow.

5. It provides an effective way of inserting and deleting objects.

6. It is also called as Linked List or Link List.

7. Link list is implemented using a list container.

8. It is a dynamic data structure.

9. It can expand and shrink its size at run time according to its requirement.

10. It can expand by allocating memory while shrink by deallocating memory.

How to Create a List Object?

list <int> LIST1;

list <int> LIST2 {11, 22, 33, 44};

list <string> LIST3 {"India", "Bihar", "Samastipur"};

Useful Functions of List Class

1. sort() : it sorts the list in ascending or descending order.
2. size() : it shows the size of the list.
3. push_back() : it adds the element at the last of the list.
4. push_front() : it adds the element at the front of the list.
5. pop_back() : it deletes the last element of the list.
6. pop_front() : it deletes the first element of the list.
7. reverse() : it reverses all the elements of the list.
8. remove() : it removes the element from the list.
9. clear() : it empties the list by deleting all the list elements.

using namespace std;
int main(){
 list <int> list1 {11, 22, 33, 44};
 list <string> list2 {"India", "is", "my", "country."};
 // iterator use to print the list value
 list<int> :: iterator P=list1.begin();
 while (P!=list1.end()) {
  cout << *P << " ";    // 11 22 33 44
 cout << "Total Values:" << list1.size();  // Total Values: 4
 list2.push_back("Bhopal");    //add at last
 list2.push_front("Bihar");    //add at front
 list1.pop_back();     //delete last element
 list1.pop_front();    //delete first element
 list1.sort();       //arrange in ascending order
 list1.reverse();    //reverse all elements in the list
 list1.remove(44);   //remove 44 from the list
 list1.clear();      //empty the list

<< Previous                                                                                      Next >>


Post a Comment

* Please Don't Spam Here. All the Comments are Reviewed by Admin.