For working professionals
For fresh graduates
More
Explore C++ Tutorials: Explori…
1. The Ultimate C++ Guide: C++ Tutorial for Beginners
2. Application of C++
3. C++ Hello World Program
4. C++ Variable
5. Reference Variable in C++
6. Function Overloading in C++
7. Functions in C++
8. Pointer in C++
9. Data Types in C++
10. C++ for Loop
11. While Loop in C++
12. C++ Lambda
13. Loop in C++
14. Switch Case in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
18. Class and Object in C++
19. Constructor in C++
20. Copy Constructor in C++
21. Destructor in C++
22. Multiple Inheritance in C++
23. Encapsulation in C++
24. Single Inheritance in C++
25. Friend Class in C++
26. Hierarchical Inheritance in C++
27. Virtual Base Class in C++
28. Abstract Class in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
32. Initialize Vector in C++
33. Iterators in C++
34. Queue in C++
35. Priority Queue in C++
36. Stack in C++
37. ifstream in C++
38. Exception Handling in C++
39. Memory Management in C++
40. Templates in C++
41. Type Conversion in C++
42. Enumeration in C++
43. Namespace in C++
44. Set Precision in C++
45. Stringstream in C++
46. Recursion in C++
47. Random Number Generator in C++
48. C++ Shell
49. Setw in C++
50. Multithreading in C++
51. Atoi in C++
52. Call by Value and Call by Reference in C++
53. Difference Between C and C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
59. Power Function in C++
60. Data Hiding in C++
61. Inline Function in C++
62. Getline Function in C++
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
Now Reading
67. static_cast in C++
68. C++ Comments
69. Structures in C++
70. C++ Standard Template Library (STL)
71. Virtual Function in C++
72. Sorting in C++
73. Polymorphism in C++
74. Oops Concepts in C++
75. Converting Integers to Strings in C++
76. Differences Between Break and Continue
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.
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.
Here is where lists outshine those rigid arrays:
Reach for lists when you encounter situations like these:
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.
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;
Let us populate our std list C++:
To reshape our C++ list, let us remove some elements:
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();
}
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:
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.
Let's explore some C++ library list operations that you'll frequently perform.
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;
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;
}
The clear() function erases all the elements from your list, leaving you with an empty container.
Example:
numbers.clear();
The reverse() function flips the order of the elements in your C++ list.
Example:
numbers.reverse();
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.
Here are some advanced C++ list techniques that will take your C++ programming skills to the next level.
The splice() function lets you surgically move elements from one list to another. There are a few ways it can be used:
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}
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();
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;
}
Here are some additional C++ list functions:
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;
}
Here are two examples of using C++ lists:
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:
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;
};
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.
Let us cover some tips and best practices.
We should use lists when:
We should use vectors when:
We should use arrays when:
Lists' Strengths:
Lists' weakness:
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 |
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.
A C++ list is a dynamic data structure within the Standard Template Library (STL) that stores an ordered sequence of elements.
Yes, C++ has a list class (std::list) within the <list> header.
You create a list in C++ by including the <list> header and declaring a list object: #include <list>; std::list<data_type> list_name;
Use the following functions to add elements:
Use these functions to remove elements:
Yes, the std::list in C++ is typically implemented as a doubly-linked list.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.