A std::list is a container class in the C++ Standard Template Library (STL) that
stores a doubly-linked list of elements. Like a std::vector and std::deque,
std::list provides automatic memory management and dynamic resizing, but unlike
these containers, it allows for efficient insertion and removal of elements
anywhere within the list.
Here is an example of creating and using a std::list:
Copy code
#include <list>
#include <iostream>
int main() {
// Create a list of integers
std::list<int> myList;
// Add the numbers 1-5 to the list
for (int i = 1; i <= 5; i++) {
myList.push_back(i);
}
// Print the list
for (auto i : myList) {
std::cout << i << " ";
}
std::cout << std::endl;
// Insert the number 6 at the 3rd position in the list
auto it = myList.begin();
std::advance(it, 2);
myList.insert(it, 6);
// Print the list
for (auto i : myList) {
std::cout << i << " ";
}
std::cout << std::endl;
// Remove the 4th element from the list
it = myList.begin();
std::advance(it, 3);
myList.erase(it);
// Print the list
for (auto i : myList) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
This program creates a std::list called myList. It then uses a for loop to add
the numbers 1-5 to the list using the push_back() function. After that it will
print the list using range based for loop. Then it will insert the number 6 at the
3rd position in the list using insert() function and std::advance() function to
get the iterator at the desired position. After that it will print the list again,
and finally it will remove the 4th element from the list using the erase() function.
As we can see, the difference between std::vector, std::deque and std::list is that
std::list allows for efficient insertion and removal of elements anywhere within
the list, whereas std::vector and std::deque only allows insertion and removal of
elements at the back.
To embed this project on your website, copy the following code and paste it into your website's HTML: