C++ List
In C++, a list is a sequence container that allows non-contiguous memory allocation. Lists are part of the Standard Template Library (STL) and provide a way to store elements in a doubly linked list format, allowing for efficient insertion and deletion of elements.
Key Topics
Overview of Lists
Lists provide several advantages:
- Efficient insertions and deletions from both ends.
- Elements can be added or removed without reallocating the entire list.
- Supports bidirectional iteration.
Declaring Lists
To declare a list, include the list
header and use the following syntax:
#include
list myList;
Common List Operations
Here are some common operations you can perform on lists:
push_back()
: Adds an element to the end of the list.push_front()
: Adds an element to the front of the list.pop_back()
: Removes the last element from the list.pop_front()
: Removes the first element from the list.size()
: Returns the number of elements in the list.clear()
: Removes all elements from the list.
Example: Basic List Operations
#include
#include
using namespace std;
int main() {
list myList;
myList.push_back(10);
myList.push_front(20);
myList.push_back(30);
cout << "List size: " << myList.size() << endl;
myList.pop_front();
cout << "List size after pop_front: " << myList.size() << endl;
myList.clear();
cout << "List size after clear: " << myList.size() << endl;
return 0;
}
Output:
List size: 3
List size after pop_front: 2
List size after clear: 0
Iterating Over Lists
You can iterate over the elements of a list using an iterator or a range-based for loop.
Example: Iterating with a Range-Based For Loop
#include
#include
using namespace std;
int main() {
list myList = {10, 20, 30, 40, 50};
cout << "List elements: ";
for (int num : myList) {
cout << num << " ";
}
return 0;
}
Output:
List elements: 10 20 30 40 50
Example: Iterating with Iterators
#include
#include
using namespace std;
int main() {
list myList = {10, 20, 30, 40, 50};
cout << "List elements using iterators: ";
for (auto it = myList.begin(); it != myList.end(); ++it) {
cout << *it << " ";
}
return 0;
}
Output:
List elements using iterators: 10 20 30 40 50
Exercises with Lists
Here are some exercises to practice your understanding of lists:
- Create a list of strings and store names. Print each name using a range-based for loop.
- Write a program that reads integers from the user and stores them in a list until the user enters -1. Then, print the sum of the entered integers.
- Implement a function that takes a list and returns the maximum element.
Key Takeaways
- Lists are sequence containers that allow efficient insertions and deletions.
- Lists are implemented as doubly linked lists, providing bidirectional iteration.
- Common operations include adding, removing, and accessing elements, as well as checking the size of the list.
- Practice exercises can help solidify your understanding of how to use lists effectively in C++.