C++STL容器之list和常用接口的实现
作者:野牛程序员:2024-01-03 20:40:48 C++阅读 2590
list
是 C++ 标准模板库(STL)中的一种容器,它是一个双向链表,可以在两端高效地插入和删除元素。以下是 list
常用接口的一些实现:
构造函数和析构函数:
#include <list> // 默认构造函数 std::list<int> myList; // 指定大小和初始值的构造函数 std::list<int> myListWithSize(5, 10); // 创建包含 5 个元素,每个元素值为 10 // 使用迭代器范围构造函数 std::list<int> anotherList(myList.begin(), myList.end()); // 复制构造函数 std::list<int> copyList(anotherList); // 析构函数会自动释放 list 占用的内存
插入和删除元素:
#include <list> std::list<int> myList; // 在链表末尾插入元素 myList.push_back(42); // 在链表开头插入元素 myList.push_front(10); // 在指定位置插入元素 auto it = std::next(myList.begin()); // 获取第二个元素的迭代器 myList.insert(it, 25); // 删除指定位置的元素 auto eraseIt = std::next(myList.begin()); myList.erase(eraseIt); // 删除链表末尾的元素 myList.pop_back(); // 删除链表开头的元素 myList.pop_front();
访问元素:
#include <list> std::list<int> myList = {10, 20, 30, 40, 50}; // 访问第一个和最后一个元素 int firstElement = myList.front(); int lastElement = myList.back(); // 通过迭代器访问元素 auto it = std::next(myList.begin(), 2); // 获取第三个元素的迭代器 int thirdElement = *it;
遍历列表:
#include <list> #include <iostream> std::list<int> myList = {1, 2, 3, 4, 5}; // 使用迭代器遍历列表 for (auto it = myList.begin(); it != myList.end(); ++it) { std::cout << *it << " "; } // 使用范围-based for 循环遍历列表 for (const auto& element : myList) { std::cout << element << " "; }
这些是 list
容器的一些常用接口及其简单实现。请注意,list
不提供随机访问,因此访问和修改元素的操作通常需要通过迭代器进行。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
