C++ List

In C++, the std::list is a sequence container that enables the non-contiguous storage of elements. It is implemented as a doubly linked list , where every element contains the address of both the next and previous list elements. It allows us to store the data in non-contiguous memory, which provides fast insertion and deletion at any position if the position is known.

Unlike the std::vector , which contains the elements in contiguous memory and enables fast random access, a list provides support for sequential access, which means the element should be accessed by traversing from the front and back.

The std::list supports bidirectional access and provides an efficient way for insertion and deletion operations. However, traversal is slow in the list because list elements are accessed sequentially, while a vector supports random access.

Syntax

It has the following syntax:

Example

list<type> list_name;

In this syntax,

  • type: It represents the type of elements in the list.
  • list_name: It represents the name that is assigned to the list.
  • Initialization of List

The list can be initialised in two ways.

Example

list<int>  new_list{1,2,3,4};
Example

list<int> new_list = {1,2,3,4};

C++ Declaration and Initialization List Example

Let us take an example to illustrate how we can declare and initialize the list in C++.

Example

Example

#include <iostream>

#include <string.h>

using namespace std;  //using standard namespace

class Test{

public:

int hno;

string city, state;

Test( int hno, string city, string state )

{ this->hno = hno;

this->city = city;

this->state = state;

}

};

class Address

{

private:

Test* addr;

public:

string name;

Address( string name, Test* addr )

{	

this->name = name;

this->addr = addr;

}

void display( )

{

cout<< " Name : " << name << " \n " << " Hno : " << addr->hno << " \n " << " City : " << addr->city << " \n " << " State : " << addr->state << endl << " ------------------------- " << endl;

}

};

int main( ) {

Test obj1= Test( 45 ,"Los Angeles","USA" );

Test obj2 = Test( 65, " London","UK" );

Address a1 = Address( "Joy",&obj1 );

Address a2 = Address( "Jack",&obj2 );

cout << " Below are the details : " << endl << " ------------------------------ " << endl;

a1.display( );

a2.display( );

return 0;

}

Output:

Output

10 20 30

Explanation:

In this example, we use various ways to declare and initialize std::list, including using an initializer list, specifying repeated values, and copying from another list. After that, we use a range-based for loop to traverse and print the elements of list2.

Basic Operations of C++ List

There are several operations that are performed on std::list in C++. Some main operations are as follows:

1) push_back and push_front

In C++, the pushback function appends an element to the end, and the pushfront function inserts at the beginning. It is suitable for queue and deque-like behaviours.

C++ pushback and pushfront Function Example

Let us take an example to illustrate the pushback and pushfront functions in C++.

Example

Example

#include <iostream>

#include <list>     // Required for std::list

#include <string>   // Required for std::string

using namespace std;   //using standard namespace

void printList(const list<int>& lst, const string& msg) {

    cout << msg;

    for (int val : lst) cout << val << " ";

    cout << "\n";

}

int main() {   //main function

    list<int> myList;

    printList(myList, "Initial list: ");

    myList.push_back(30);

    printList(myList, "After push_back(30): ");

    myList.push_front(10);

    printList(myList, "After push_front(10): ");

    myList.push_back(40);

    printList(myList, "After push_back(40): ");

    myList.push_front(5);

    printList(myList, "After push_front(5): ");

    return 0;

}

Output:

Output

Initial list: 

After push_back(30): 30 

After push_front(10): 10 30 

After push_back(40): 10 30 40 

After push_front(5): 5 10 30 40

Explanation:

In this example, we demonstrate the std::list container by inserting elements at both the front and back using the pushfront and the pushback functions. After that, we have taken a printList function that is utilized after every insertion to show the current state of the list with a custom message.

2) pop_front and pop_back

In C++, the popfront function is used to remove the first element, and the popback function is used to remove the last element from the list. These functions are also used to shrink lists from either end.

C++ List Example using popfront and popback function

Let us take an example to illustrate the popfront and popback functions in C++.

Example

Example

#include <iostream>

#include <list>

#include <string>

using namespace std;   //using standard namespace

void printList(const list<int>& lst, const string& msg) {

    cout << msg;

    for (int val : lst) cout << val << " ";

    cout << "\n";

}

int main() {   //main function

    list<int> myList = {10, 20, 30, 40, 50};

    printList(myList, "Original list: ");

    myList.pop_front();

    printList(myList, "After pop_front(): ");

    myList.pop_back();

    printList(myList, "After pop_back(): ");

    myList.pop_back();

    printList(myList, "After another pop_back(): ");

    return 0;

}

Output:

Output

Original list: 10 20 30 40 50 

After pop_front(): 20 30 40 50 

After pop_back(): 20 30 40 

After another pop_back(): 20 30

Explanation:

In this example, we demonstrate how to remove elements from a std::list using the popfront and popback function. After that, the printList function shows the list after every operation. First, the list contains five elements and then elements are removed from the front and back using popfront and popback functions to show how the list changes dynamically.

3) insert

In C++, we can insert elements anywhere using iterators. It allows us to add new elements before a specific position.

C++ List Example using insert function

Let us take an example to illustrate the insert function in C++.

Example

Example

#include <iostream>

#include <list>

#include <string>

using namespace std;  //using standard namespace

void printList(const list<int>& lst, const string& msg) {

    cout << msg;

    for (int val : lst) cout << val << " ";

    cout << "\n";

}

int main() {   //main function

    list<int> myList = {10, 20, 40};

    printList(myList, "Initial list: ");

    auto it = myList.begin();

    ++it; // points to 20

    myList.insert(it, 15);

    printList(myList, "After insert(15) before 20: ");

    it = myList.end();

    myList.insert(it, 50);

    printList(myList, "After insert(50) at end: ");

    it = myList.begin();

    myList.insert(it, 5);

    printList(myList, "After insert(5) at beginning: ");

    return 0;

}

Output:

Output

Initial list: 10 20 40 

After insert(15) before 20: 10 15 20 40 

After insert (50) at end: 10 15 20 40 50 

After insert(5) at the beginning: 5 10 15 20 40 50

Explanation:

In this example, we demonstrate the insertion process of elements into a std::list at specific positions using iterators. It starts with an initial list {10, 20, 40} and then insert 15 before 20 using an iterator. After that, we insert 50 at the end using the end iterator, and insert 5 at the beginning using the begin iterator. Finally, the printList function shows the list after every insertion to display the updated elements order.

4) erase

In C++, the erase function is used to remove the element at a given position or range. After that, the iterator-based removal allows precise control.

C++ List Example using erase function

Let us take an example to illustrate the erase function using the erase function in C++.

Example

Example

#include <iostream>

#include <list>

#include <string>

using namespace std;  //using standard namespace

void printList(const list<int>& lst, const string& msg) {

    cout << msg;

    for (int val : lst) cout << val << " ";

    cout << "\n";

}

int main() {   //main function

    list<int> myList = {5, 10, 15, 20, 25, 30};

    printList(myList, "Original list: ");

    auto it = myList.begin();

    ++it; // points to 10

    myList.erase(it);

    printList(myList, "After erasing element at position 2 (10): ");

    it = myList.begin();

    advance(it, 2); // points to 20

    auto it2 = myList.end();

    advance(it2, -1); // points to 30

    myList.erase(it, it2);

    printList(myList, "After erasing elements from 20 up to 30: ");

    return 0;

}

Output:

Output

Original list: 5 10 15 20 25 30 

After erasing element at position 2 (10): 5 15 20 25 30 

After erasing elements from 20 up to 30: 5 15 30

Exaplantion:

In this example, we demonstrate how we can remove the element in C++ using the erase function with std::list. First, it initializes a list {5, 10, 15, 20, 25, 30}. After that, erase the second element (10) using an iterator. Finally, we remove a range of elements from 20 up to 30 by using erase(it, it2) with iterators. The printList function shows the state of the list after every deletion.

5) size and empty

In C++, the size function is used to return the number of elements, and the empty function checks if the list has none. It is very useful for condition checks and loops.

C++ List Example using size and empty Function

Let us take an example to illustrate the size and empty functions in C++ List.

Example

Example

#include <iostream>

#include <list>

using namespace std;  //using standard namespace

int main() {   //main function

    list<int> myList;

    cout << "Initially: Size = " << myList.size() << ", Is empty? " 

              << (myList.empty() ? "Yes" : "No") << "\n";

    myList.push_back(100);

    myList.push_back(200);

    cout << "After adding elements: Size = " << myList.size() << ", Is empty? " 

              << (myList.empty() ? "Yes" : "No") << "\n";

    return 0;

}

Output:

Output

Initially: Size = 0. Is empty? Yes

After adding elements: Size = 2, Is empty? No

Explanation

In this example, we demonstrate how to use the size and empty member functions of the list container. First, we create an empty list, and its size and empty status are displayed. After that, two integers (100 and 200) are added using the push_back function.

6) clear

In C++, the clear method is mainly used to remove all elements from the list, which makes the list empty. It is useful to reuse the list without reallocating.

C++ List Example using clear function

Let us take an example to illustrate the clear function in C++ List.

Example

Example

#include <iostream>

#include <list>

using namespace std;   //using standard namespace

int main() {   //main function

    list<int> myList = {1, 2, 3, 4, 5};

    cout << "Before clear(), size = " << myList.size() << "\n";

    myList.clear();

    cout << "After clear(), size = " << myList.size() << "\n";

    return 0;

}

Output:

Output

Before clear(), size = 5

After clear(), size = 0

Explanation:

In this example, we demonstrate the clear function of the std::list container. It starts with a list initialized with 5 integers. After that, the size of the list is printed before and after calling the clear function, which removes all elements from the list. After the clear function, the list becomes empty, and its size becomes 0.

7) sort

In C++, the sort function is mainly used to sort the list in ascending order. After that, it works only for sortable data types.

C++ List Example using the sort Function

Let us take an example to illustrate the sort function in C++ List.

Example

Example

#include <iostream>

#include <list>

#include <string>

using namespace std;  //using standard namespace

void printList(const list<int>& lst, const string& msg) {

    cout << msg;

    for (int val : lst) cout << val << " ";

    cout << "\n";

}

int main() {   //main function

    list<int> myList = {40, 10, 50, 20, 30};

    printList(myList, "Before sort: ");

    myList.sort();

    printList(myList, "After sort: ");

    return 0;

}

Output:

Output

Before sort: 40 10 50 20 30 

After sort: 10 20 30 40 50

Explanation:

In this example, we demonstrate how to sort a std::list using the sort member function. First, the list holds unsorted elements {40, 10, 50, 20, 30}. After calling myList.sort function, the list is rearranged in ascending order as {10, 20, 30, 40, 50} and displayed.

9) reverse

In C++, the reverse function is used to reverse the order of elements in the list. It does not return anything but modifies in place.

C++ List Example using reverse function

Let us take an example to illustrate the reverse function in C++.

Example

Example

#include <iostream>

#include <list>

#include <string>

using namespace std;   //using standard namespace

void printList(const list<int>& lst, const string& msg) {

    cout << msg;

    for (int val : lst) cout << val << " ";

    cout << "\n";

}

int main() {    //main function

    list<int> myList = {10, 20, 30, 40};

    printList(myList, "Before reverse: ");

    myList.reverse();

    printList(myList, "After reverse: ");

    return 0;

}

Output:

Output

Before reverse: 10 20 30 40 

After reverse: 40 30 20 10

Explanation:

In this example, we demonstrate how to reverse the elements of a list using the reverse function. First, the list contains {10, 20, 30, 40} elements. After calling the myList.reverse function, the list order becomes {40, 30, 20, 10} and then it is displayed.

9) remove(value)

In C++, the remove(value) function is used to remove all the elements that are equal to the specified value. It is an efficient way to remove duplicates or unwanted values.

C++ List Example using remove (Value) function

Let us take an example to illustrate the remove (value) function in C++ List.

Example

Example

#include <iostream>

#include <list>

#include <string>

using namespace std;   //using standard namespace

void printList(const list<int>& lst, const string& msg) {

    cout << msg;

    for (int val : lst) cout << val << " ";

    cout << "\n";

}

int main() {   //main function

    list<int> myList = {10, 20, 10, 30, 10, 40};

    printList(myList, "Original list: ");

    myList.remove(10);

    printList(myList, "After removing all 10s: ");

    return 0;

}

Output:

Output

Original list: 10 20 10 30 10 40 

After removing all 10s: 20 30 40

Explanation:

In this example, we demonstrate how to remove all occurrences of a specific value from a list. Initially, the list contains {10, 20, 10, 30, 10, 40} elements. After that, the remove(10) function call deletes all 10 values from the list, which results in {20, 30, 40}, which is then displayed.

C++ List Functions

There are several functions in C++ List. These are as follows:

Method Description
insert() It inserts the new element before the position pointed by the iterator.
push_back() It adds a new element at the end of the vector.
push_front() It adds a new element to the front.
pop_back() It deletes the last element.
pop_front() It deletes the first element.
empty() It checks whether the list is empty or not.
size() It finds the number of elements present in the list.
max_size() It finds the maximum size of the list.
front() It returns the first element of the list.
back() It returns the last element of the list.
swap() It swaps two list when the type of both the list are same.
reverse() It reverses the elements of the list.
sort() It sorts the elements of the list in an increasing order.
merge() It merges the two sorted list.
splice() It inserts a new list into the invoking list.
unique() It removes all the duplicate elements from the list.
resize() It changes the size of the list container.
assign() It assigns a new element to the list container.
emplace() It inserts a new element at a specified position.
emplace_back() It inserts a new element at the end of the vector.
emplace_front() It inserts a new element at the beginning of the list.

C++ Example Program to display various functions on List

Let us take an example to illustrate the several functions on the C++ List.

Example

Example

#include <iostream>

#include <list>

using namespace std;   //using standard namespace

int main() {   //main function

    list<int> list1 = {3, 1, 4, 1, 5};

    list<int> list2 = {2, 7, 1};

    // push_back and push_front

    list1.push_back(9);

    list1.push_front(0);

    // insert at 2nd position

    auto it = list1.begin();

    advance(it, 2);

    list1.insert(it, 8);

    // emplace and emplace_front

    list1.emplace(it, 6);         // Inserts before iterator

    list1.emplace_front(-1);      // Inserts at front

    // pop operations

    list1.pop_back();

    list1.pop_front();

    // front and back

    cout << "Front: " << list1.front() << ", Back: " << list1.back() << endl;

    // size, max_size, empty

    cout << "Size: " << list1.size() << ", Max Size: " << list1.max_size() << endl;

    cout << "Is Empty: " << (list1.empty() ? "Yes" : "No") << endl;

    // sort and unique

    list1.sort();

    list1.unique();

    // reverse

    list1.reverse();

    // assign new values

    list2.assign(3, 10);  // 10 10 10

    // resize

    list2.resize(5, 99);  // fills with 99

    // merge list2 into list1 (both must be sorted)

    list1.sort();

    list2.sort();

    list1.merge(list2);

    // splice (move elements from one list to another)

    list<int> list3 = {50, 60};

    list1.splice(list1.begin(), list3);  // moves list3 to front of list1

    // swap

    list<int> list4 = {100, 200};

    list1.swap(list4);

    // Final Output

    cout << "Final list4 after swap (was list1): ";

    for (int x : list4) cout << x << " ";

    cout << endl;

    cout << "Final list1 after swap (was list4): ";

    for (int x : list1) cout << x << " ";

    cout << endl;

    return 0;

}

Output:

Output

Front: 0, Back: 5

Size: 8, Max Size: 384307168202282325

Is Empty: No

Final list4 after swap (was list1): 50 60 0 1 3 4 5 6 8 10 10 10 99 99 

Final list1 after swap (was list4): 100 200

Explanation:

In this example, we demonstrate how to manipulate a std::list using several functions, including insert, emplace, splice, sort, merge, etc. Every method displays a specific list operation, such as insertion, deletion, modification, or merging of lists. After that, the swap method exchanges the content of two lists and reflects the complete changes and transfer of data between them.

C++ List MCQs

1) Which of the following statements matches the functionality of std::list's splice function in C++?

  • It tests each item in the list against a condition and removes those that fit.
  • It copies each element from one list and puts them into the other list.
  • It can quickly move elements from one list to another without the need to copy or move them.
  • It deletes a specified range of elements, saves them as a separate list and returns the new list.

2) When we apply unique function to a list where the duplicates are not next to each other, what does it return?

  • It deletes all occurrences of the same element, no matter where it originally appeared in the list.
  • This algorithm only takes out the first match of a repeated element within the list.
  • After sorting, the code removes all items that appear more than once in the list.
  • It deletes just those duplicate elements that are next to each other.

3) When two std::list containers are used with the merge function, what does the function do?

  • Adds the second list to the end of the first list, regardless of how the lists are arranged.
  • Combines two sorted lists into another single sorted list with the data already in order.
  • Arrange both lists in order before merging them without intervention.
  • Produces a new list containing elements arranged in descending order from both the original lists.

4) When should we consider std::vector over std::list while selecting a container in C++?

  • If the code must frequently insert and delete items right at the ends of the container.
  • If we need to organize the elements more than once.
  • When we need to access the elements in an array by using an index number.
  • When we need the collection to expand or shrink based on its contents.

5) What is the result if we sort a list of custom objects without declaring any comparison function?

  • The program will organize the objects by the memory address assigned to them.
  • A compile-time error is produced when there is no operator (<) present in the program.
  • The list will not be sorted and will remain unchanged.
  • An error will be raised during runtime because we forgot to include a comparison check.

Input Required

This code uses input(). Please provide values below: