Lists
Introduction to Lists in Standard Template Library (STL)
Hello there! Today, we are going to dive into an interesting topic in C++ programming. We will explore the concept of 'Lists' under the 'Standard Template Library' (STL). By the end of this tutorial, you should have a comprehensive understanding of how lists function in C++ and how you can use them to streamline your coding process. Let's get started!
What is a List in C++ STL?
A list in C++ STL is a type of sequence container. The list container is designed to allow fast insertions and deletions of elements from any position within the sequence. Unlike vectors and arrays, lists are doubly-linked lists meaning they can be iterated forward and backward.
How to Include List in Your Program
To use lists in your C++ program, you need to include the list header file. Here’s how to include it:
#include <list>
Declaring a List
A list in C++ STL is declared as:
std::list<datatype> listname;
Where datatype
is the type of data to be stored and listname
is the name of the list.
List Operations
Let’s now dive into the different operations that can be performed on a list.
1. Insertion
Insertion can be done at the end, beginning or any position in the list.
std::list<int> myList;
myList.push_front(10); // Inserts 10 at the beginning
myList.push_back(20); // Inserts 20 at the end
2. Deletion
Deletion can also be done at the end, beginning or any position in the list.
myList.pop_front(); // Deletes the first element
myList.pop_back(); // Deletes the last element
3. Accessing Elements
Unlike vectors and arrays, lists do not support direct access to elements by their position. To access elements, iteration through the list is required.
std::list<int>::iterator it;
for(it = myList.begin(); it != myList.end(); it++)
{
std::cout << *it << " ";
}
4. Size of the List
To find the number of elements in the list, we use the size() function.
std::cout << "Size of the list is: " << myList.size();
5. Checking if List is Empty
To check if the list is empty or not, we use the empty() function.
if(myList.empty())
std::cout << "List is Empty";
else
std::cout << "List is not Empty";
6. Sorting the List
To sort the list, we use the sort() function.
myList.sort();
7. Reversing the List
To reverse the list, we use the reverse() function.
myList.reverse();
That’s all for today on lists in C++ STL. Feel free to experiment with the different operations and get comfortable with lists. Happy coding!