View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
C++ Tutorial

Explore C++ Tutorials: Explori…

  • 76 Lessons
  • 15 Hours

C++ List

Updated on 04/02/2025343 Views

We can think of using a C++ list like using a chain of versatile boxes where we can add boxes, remove boxes, or rearrange them in the blink of an eye. Unlike those rigid arrays, lists let our data flow and adapt effortlessly.

If you manage things like to-do lists, recent website history, or anything where order and easy change matter, then C++ lists are your new best friend. Let us dive in and learn everything about using C++ lists.

What is a C++ List?

Lists help us work with dynamic data structures. They belong to the Standard Template Library (STL), which is like a toolbox of powerful coding tools. Lists are fundamentally a chain of elements where you can insert or remove items anywhere along the chain with remarkable ease.

Why Use Lists?

Here is where lists outshine those rigid arrays:

  • Flexibility: Need to add or remove items in the middle of your data? Lists do this effortlessly without disrupting the rest of the elements.
  • Efficiency in movement: Lists are designed for smooth navigation. Whether you want to go from beginning to end or back again, lists are optimized for that.
  • No size limits: Lists don't have a predefined size limit. Your data can grow or shrink, and your list adapts accordingly.

When to Use Lists

Reach for lists when you encounter situations like these:

  • Queues: Think of a line at a store. Lists perfectly model "first in, first out" (FIFO) scenarios.
  • Stacks: Picture a stack of plates. Lists let you add or remove from the top, ideal for "last in, first out" (LIFO) operations.
  • Linked data: Got data with a natural chain-like structure (like a website navigation path)? Lists represent these relationships superbly.

Creating and Manipulating a C++ List

Before creating a C++ list, we must bring in the necessary tool (the headers). The #include <list> directive acts like a key that unlocks the features of the C++ list class. Always make sure to include this at the beginning of your code.

Declaring a C++ List

To create a list, we declare it like this:

std::list<data_type> list_name;

For example, if you want a list to store numbers, we would use:

std::list<int> myNumberList;

Adding Elements in a C++ List

Let us populate our std list C++:

  • push_front(): Adds a new element to the front of the list.
  • push_back(): Adds a new element to the end of the list.
  • insert(): Inserts an element at a specific position within the list. You'll need to use iterators (think of them as pointers for lists) to specify the insertion point.

Removing Elements from a C++ List

To reshape our C++ list, let us remove some elements:

  • pop_front(): Removes the element from the front of the list.
  • pop_back(): Removes the element from the end of the list.
  • remove(): This one is a bit more powerful as it removes all elements that match a value you provide.

Example:

Code:

#include <list>
#include <iostream>
int main() {
std::list<int> myNumberList;
myNumberList.push_back(10);
myNumberList.push_front(5);
myNumberList.push_back(15);
// Let's remove the first element (5)
myNumberList.pop_front();
}

Accessing C++ List Elements

Let us discuss two methods for accessing elements in a C++ programming list.

1. Using Iterators

C++ list iterator functions are like special pointers designed for lists. They are essential for navigating and accessing elements within a list.

There are:

  • begin(): This will point to the first element in the cpp list.
  • end(): This will point past the last element in the list. This is important, as it's often used as a "stop sign" when looping through a list.

Accessing elements in a C++ list example

#include <list>
#include <iostream>
int main() {
std::list<std::string> groceryList = {"Apples", "Bananas", "Milk"};
// Iterator to loop through the list
std::list<std::string>::iterator it;
for (it = groceryList.begin(); it != groceryList.end(); ++it) {
std::cout << *it << " "; // Note: Use * to "dereference" the iterator
}
std::cout << std::endl;
}

2. Direct Access (Caveats)

Unlike arrays, you can't use the familiar [] notation to directly grab an element from a list by its index (e.g., myList[2]). This is because lists are not stored in memory the same way as arrays.

Essential C++ List Operations

Let's explore some C++ library list operations that you'll frequently perform.

Determining Size: size()

The size() function is your go-to tool for finding out how many elements are currently in your list.

Example:

std::list<int> numbers;
// ... add elements ...
int numElements = numbers.size();
std::cout << "Number of elements in the list: " << numElements << std::endl;

Checking Emptiness: empty()

The empty() C++ function list tells you whether your list is empty or not. It returns 'true' if empty, 'false' otherwise.

Example:

if (numbers.empty()) {
std::cout << "The list is empty" << std::endl;
}

Clearing the List: clear()

The clear() function erases all the elements from your list, leaving you with an empty container.

Example:

numbers.clear();

Reversing a List: reverse()

The reverse() function flips the order of the elements in your C++ list.

Example:

numbers.reverse();

Sorting a List: sort()

The sort() function arranges the elements of your list in ascending order (or you can provide a custom comparison function for more complex sorting).

Example:

numbers.sort();

Using these operations in a C++ compiler list example:

Code:

#include <list>
#include <iostream>
int main() {
std::list<int> numbers = {3, 1, 5, 2};
std::cout << "Original list: ";
for (int num : numbers) {
std::cout << num << " ";
}
// Reverse and sort the list
numbers.reverse();
numbers.sort();
std::cout << "\nList after reversing and sorting: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
}

If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.

Advanced C++ List Techniques

Here are some advanced C++ list techniques that will take your C++ programming skills to the next level.

Splicing Lists: splice()

The splice() function lets you surgically move elements from one list to another. There are a few ways it can be used:

  • Transfer all elements: Move an entire list into another.
  • Transfer single element: Move a single element specified by an iterator.
  • Transfer range: Move a range of elements determined by iterators.

Merging Sorted Lists: merge()

The merge() function efficiently combines two already sorted lists into a single sorted list. This saves you from having to manually sort after combining.

Example:

std::list<int> list1 = {1, 4, 6};
std::list<int> list2 = {2, 3, 5};
list1.merge(list2); // list1 now contains {1, 2, 3, 4, 5, 6}

Removing Duplicates: unique()

The unique() function cleans up your list by removing consecutive duplicate elements. It's often used after sorting to make duplicates adjacent.

Example:

std::list<int> numbers = {1, 2, 2, 3, 3, 3, 4};
numbers.sort();
numbers.unique();

Custom Data Types

C++ lists are incredibly versatile. We can store objects of our own classes within them. Just make sure your class has appropriate comparison operators defined (like < or ==) if you want to use functions like sort() or unique().

Example:

Code:

#include <list>
#include <iostream>
int main() {
std::list<int> list1 = {1, 3, 5};
std::list<int> list2 = {2, 4};
// Insert all elements of list2 at the beginning of list1
list1.splice(list1.begin(), list2);
std::cout << "Spliced list: ";
for (int num : list1) {
std::cout << num << " ";
}
std::cout << std::endl;
}

Additional C++ List Functions

Here are some additional C++ list functions:

  • resize(): Changes the size of the list. Use to add or remove elements from the end.
  • assign(): Replaces the contents of the list with new elements.
  • emplace_front(), emplace_back(): Similar to push functions, but constructs the element in-place for potential efficiency gains with complex objects.
  • emplace(): Like insert, but constructs the object in-place.

Example:

#include <list>
#include <iostream>
int main() {
std::list<int> numbers = {1, 2, 3};
// Resize to 5 elements, default value (0) is used for new elements
numbers.resize(5);
// Assign 4 elements with the value 10
numbers.assign(4, 10);
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
}

C++ List Real-World Examples

Here are two examples of using C++ lists:

Implementing a Queue

Queues follow the "First-In, First-Out" (FIFO) principle. Think of a waiting line, the first person to join is the first to be served.

Using C++ lists:

  • push_back() is perfect for adding elements to the "end" of the queue.
  • pop_front() efficiently removes from the "front" of the queue.

Example:

#include <list>
#include <iostream>
class Queue {
public:
void enqueue(int data) {
items.push_back(data);
}
int dequeue() {
if (items.empty()) {
// Handle empty queue error
}
int value = items.front();
items.pop_front();
return value;
}
private:
std::list<int> items;
};

Undo/Redo Functionality

Allowing users to undo and redo actions is common in text editors, design software, etc. We can have two lists: undoList and redoList and each action is "recorded" on the undoList. When "Undo" is pressed, the last action is popped from undoList, reversed if needed, and pushed onto the redoList. Redo does the opposite.

C++ List Tips and Best Practices

Let us cover some tips and best practices.

Choosing Lists vs. Other Data Structures

We should use lists when:

  • Frequent insertions or deletions are needed, especially in the middle of the sequence.
  • You don't need direct access to elements by index.
  • Your data size is unknown or likely to change significantly.

We should use vectors when:

  • You need lightning-fast random access by index (like myArray[10]).
  • Your data size is pretty well-defined and stable.
  • Memory efficiency is a top priority

We should use arrays when:

  • You have a fixed-size collection of elements.
  • The focus is on raw performance for simple data types.

Performance Considerations

Lists' Strengths:

  • Insertion/removal anywhere in the list is usually very fast (constant time).
  • Traversal/iteration is efficient.

Lists' weakness:

  • No direct random access with []. Finding a specific element by index requires iterating. Linked lists have slightly more memory overhead than arrays or vectors due to storing pointers for the linked structure.

Quick comparison table:

Feature

Lists

Arrays

Vectors

Insertion/Removal (middle)

Fast

Very Slow

Fast

Random Access by Index

Slow

Fast

Fast

Memory Overhead

Moderate

Low

Moderate

Final Tips

By now, you are fully armed with the power to use lists in C++ effectively. Whether you're building flexible queues, crafting smart undo/redo systems, or simply want your data to dance dynamically, lists offer the tools you need.

Remember, the key is thinking about how your data needs to grow, shrink, and rearrange itself. If change is in the picture, you can definitely consider the versatile C++ list. And as your projects get more complex, don't be afraid to explore those advanced techniques and they will unlock even more possibilities.

If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.

Frequently Asked Questions

  1. What is a C++ list?

A C++ list is a dynamic data structure within the Standard Template Library (STL) that stores an ordered sequence of elements.

  1. Does C++ have a list class?

Yes, C++ has a list class (std::list) within the <list> header.

  1. How do I create a list in C++?

You create a list in C++ by including the <list> header and declaring a list object: #include <list>; std::list<data_type> list_name;

  1. How do I add elements to a C++ list?

Use the following functions to add elements:

  • push_front(): Adds to the front.
  • push_back(): Adds to the end.
  • insert(): Adds at a specific position.
  1. How do I remove elements from a C++ list?

Use these functions to remove elements:

  • pop_front(): Removes from the front.
  • pop_back(): Removes from the end.
  • remove(): Removes elements with a specific value.
  1. Is C++ list a linked list?

Yes, the std::list in C++ is typically implemented as a doubly-linked list.

  1. What are the advantages of using a C++ list?
  • Efficient insertions and deletions: Adding/removing anywhere in the list is fast.
  • No fixed size: Lists can grow or shrink as needed.
  1. What are the disadvantages of using a C++ list?
  • No random access: You can't directly access elements by index (like array[5]).
  • Memory overhead: Linked lists can have slightly more memory overhead compared to arrays.
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.