list in c++

To create a list in C++, you can use the standard template library (STL) container called std::list. Below are the steps to create a list in C++:

  1. Include the necessary header file: c++ #include <list>

  2. Declare a list object: c++ std::list<int> myList;

In this example, we are creating a list of integers (int), but you can replace it with any other data type.

  1. Add elements to the list using the push_back or push_front functions: c++ myList.push_back(10); // Adds 10 to the end of the list myList.push_front(5); // Adds 5 to the beginning of the list

You can use either push_back to add elements to the end of the list or push_front to add elements to the beginning of the list.

  1. Access elements in the list using iterators: c++ std::list<int>::iterator it; for (it = myList.begin(); it != myList.end(); ++it) { std::cout << *it << " "; }

Here, we declare an iterator it and use a for loop to iterate over the list from the beginning (myList.begin()) to the end (myList.end()). We use the *it to access the value at each position.

  1. Remove elements from the list using the erase function: c++ myList.erase(myList.begin()); // Removes the first element in the list myList.erase(myList.end()); // Removes the last element in the list

The erase function is used to remove elements from the list. In this example, we remove the first and last elements.

  1. Get the size of the list using the size function: c++ int size = myList.size();

The size function returns the number of elements in the list, which we can then store in a variable.

This is a basic example of how to create and manipulate a list in C++. Remember to include the necessary header file, declare the list object, add elements, access elements using iterators, remove elements, and get the size of the list as needed.