C++ - List Part 1: Introduction to std::list
The std::list is a container that stores elements as nodes in a doubly-linked structure. Each node contains the data and pointers to the previous and next nodes.
Examples and Explanation
Declaring and Initializing a List
#include <iostream>
#include <list>
int main() {
std::list<int> myList; // Empty list
std::list<int> myList2 = {1, 2, 3}; // List with initial values
std::list<int> myList3(5, 10); // 5 elements, each initialized to 10
return 0;
}
Explanation: Lists can be initialized empty, with specific values, or with a specified size and default value.
Accessing Elements
for (int val : myList2) {
std::cout << val << " ";
}
// Output: 1 2 3
Explanation: Lists do not support random access (e.g., myList[0]) but can be traversed using loops or iterators.
Checking Size
std::cout << "Size: " << myList2.size();
Explanation: The size() method returns the number of elements in the list.