📜  c++ list add (1)

📅  最后修改于: 2023-12-03 15:13:54.530000             🧑  作者: Mango

C++ List Add

Introduction

In C++, a list is a container that allows fast insertion and deletion of elements anywhere within the list. This introductory guide will provide you with a comprehensive overview of the list data structure and how to add elements to it in C++.

Syntax

To declare a list in C++, you need to include the <list> header file:

#include <list>

After that, you can define a list using the following syntax:

std::list<DataType> myList;

Replace DataType with the actual data type you want to store in the list. For example, to create a list of integers, you can use:

std::list<int> myList;
Adding Elements to a List

There are multiple ways to add elements to a C++ list:

1. Push Back

To add an element to the end of the list, you can use the push_back() function:

myList.push_back(element);

Replace element with the value you want to add. Here's an example:

std::list<int> myList;
myList.push_back(10);
myList.push_back(20);
myList.push_back(30);
2. Push Front

To add an element to the beginning of the list, you can use the push_front() function:

myList.push_front(element);

Replace element with the value you want to add. Here's an example:

std::list<int> myList;
myList.push_front(5);
myList.push_front(4);
myList.push_front(3);
3. Insert

To insert an element at a specific position in the list, you can use the insert() function:

myList.insert(iterator, element);

Replace iterator with an iterator pointing to the desired position and element with the value you want to insert. Here's an example:

std::list<int> myList;
auto it = myList.begin();
myList.insert(it, 15);  // Insert 15 at the beginning
it++;                   // Move the iterator to the second position
myList.insert(it, 25);  // Insert 25 at the second position
Conclusion

Congratulations! You now have a solid understanding of how to add elements to a list in C++. You can use the push_back(), push_front(), or insert() functions based on your requirements. Lists are a versatile data structure that provide efficient element insertion and deletion capabilities. Happy coding!