《21天学通C++》(第十八章)STL list和forward_list

2024-05-07 15:36

本文主要是介绍《21天学通C++》(第十八章)STL list和forward_list,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

std::list的特点
1.插入和删除操作高效:在任意位置插入或删除元素的开销是 O(1),不需要像 std::vector 那样可能需要移动大量元素。
2.不支持随机访问:访问 std::list 中的元素需要从头开始遍历到所需位置,访问特定元素的时间复杂度为O(n)

1.实例化list

实例化vector时,要指定该动态数组中存储的对象类型

std::list<int> intList;
std::list<float> floatList;

2.在开头和末尾插入元素

使用push_front()push_back()

std::list<int> intList;// 在尾部添加元素intList.push_back(10);intList.push_back(20);// 在头部添加元素intList.push_front(5);

3.列表初始化

std::list<int> myList = {1, 2, 4, 5};

4.使用insert()在中间插入元素

插入单个元素

void insert(const_iterator position, const value_type& value);
//第一个是插入位置的迭代器,第二个是值
#include <iostream>
#include<list>int main() {std::list<int> myList = {1, 2, 4, 5};auto itBegin = myList.begin(); // 获取开始迭代器auto itEnd=myList.end();//获取末尾迭代器myList.insert(itBegin,0);  // 在开头插入新元素0myList.insert(itEnd,6);//在末尾插入新元素6std::advance(itBegin,2);//将迭代器移动到第三个元素的位置myList.insert(itBegin,55);//在第三个元素之前插入新元素55for(int num:myList){std::cout<<num<<std::endl;}system("pause");return 0;
}

插入多个相同元素

void insert(const_iterator position, size_type count, const value_type& value);
//第一个是插入位置的迭代器,第二个是插入元素的数量,第三个是值
#include <iostream>
#include<list>int main() {std::list<int> myList = {1, 2, 4, 5};auto itBegin = myList.begin(); // 获取开始迭代器auto itEnd=myList.end();//获取末尾迭代器myList.insert(itBegin,3,0);  // 在开头插入3个0myList.insert(itEnd,2,6);//在末尾插入2个6std::advance(itBegin,2);//将迭代器移动到第三个元素的位置myList.insert(itBegin,2,55);//在第三个元素之前插入2个55for(int num:myList){std::cout<<num<<std::endl;}system("pause");return 0;
}

范围插入(例如列表或数组)

template<class InputIt>//需要使用模板函数
void insert(const_iterator position, InputIt first, InputIt last);
//第一个是插入位置的迭代器
//first和last是要插入元素范围的迭代器
#include <iostream>
#include<list>int main() {std::list<int> myList = {1, 2, 4, 5};auto itBegin = myList.begin(); // 获取myList开始迭代器auto itEnd=myList.end();//获取myList末尾迭代器std::list<int> secList={11,22,33};//新的listmyList.insert(itEnd,secList.begin(),secList.end());//在myList末尾插入secListfor(int num:myList){std::cout<<num<<std::endl;}system("pause");return 0;
}

5.删除list中的元素

使用erase()

删除单个元素

void erase(const_iterator position);//指向要删除元素的迭代器

删除元素范围

void erase(const_iterator first, const_iterator last);
//first指范围开始的迭代器,last指范围结束的迭代器
#include <iostream>
#include<list>int main() {std::list<int> myList = {1, 2, 3, 4, 5};// 删除单个元素auto it = myList.begin();//获取开始迭代器std::advance(it, 2); // 移动开始迭代器到第三个元素myList.erase(it); // 删除第三个元素for (const auto& value : myList) {std::cout << value << std::endl;}std::cout<<std::endl;//空一行方便观察// 删除元素范围it = myList.begin();std::advance(it, 1);//将开始迭代器移动到第二个元素auto itEnd = myList.end();//获取结束迭代器std::advance(itEnd, -1); // 移动迭代器到倒数第二个元素myList.erase(it, itEnd); // 删除从第二个元素到倒数第二个元素的范围// 打印 list 中的所有元素for (const auto& value : myList) {std::cout << value << std::endl;}system("pause");return 0;
}

6.对list中的元素进行反转和排序

①反转使用reverse()函数

#include <iostream>
#include <list>int main() {std::list<int> myList = {1, 2, 3, 4, 5};// 反转列表myList.reverse();// 打印反转后的列表std::cout << "Reversed list: ";for (int num : myList) {std::cout << num << " ";}system("pause");return 0;
}

②排序使用sort()函数

没有参数,默认<运算

list.sort();

使用二元谓词函数作为参数,按照指定标准进行排序

list.sort(Compare);//Compare可以是以下形式//1.函数指针
bool Compare(const Type& a, const Type& b);
//2.Lambda表达式
[](const Type& a, const Type& b) -> bool { /* ... */ };
//3.函数对象
struct CompareFunctor {bool operator()(const Type& a, const Type& b) const;
};
//4.std::function 对象
std::function<bool(const Type&, const Type&)> Compare;

例子

#include <iostream>
#include <list>//自定义排序函=函数
bool customCompare(int a, int b) {return a > b; // 降序排序
}int main() {std::list<int> myList = {5, 3, 6, 2, 1};// 使用默认排序myList.sort();for (int num : myList) {std::cout << num << " ";}std::cout<<std::endl;//空一行便于观察// 使用函数指针进行降序排序myList.sort(customCompare);for (int num : myList) {std::cout << num << " ";}system("pause");return 0;
}

7.对包含对象的list进行排序以及删除其中的元素

如果list的元素类型为类,而不是int等简单内置类型,又要对其包含类的属性进行排序。

①假设我们有一个简单的 Person 类,我们想根据人的年龄进行降序排序:

#include <iostream>
#include <list>//定义一个Person类
struct Person {std::string name;int age;Person(const std::string& name, int age) : name(name), age(age) {}//初始化
};//自定义年龄比较函数
bool compareByAge(const Person& a, const Person& b) {return a.age > b.age; // 降序排序
}int main() {//创建一个人的list,包含名字和年龄std::list<Person> peopleList = {{"Alice", 30},{"Bob", 25},{"Charlie", 35}};// 使用函数指针按年龄降序排序peopleList.sort(compareByAge);// 打印排序后的列表for (const auto& person : peopleList) {std::cout << person.name << " - " << person.age << std::endl;}system("pause");return 0;
}

②可以使用std::list::remove来删除满足条件的元素

#include <iostream>
#include <list>//定义Person类
struct Person {std::string name;int age;//初始化Person(const std::string& name, int age) : name(name), age(age) {}
};//自定义删除函数
bool IsOlderThan30(const Person& person) {return person.age > 30;
}int main() {//创建一个人的list,包含名字和年龄std::list<Person> peopleList = {{"Alice", 30},{"Bob", 25},{"Charlie", 35},{"Jonh", 21}};// 删除年龄大于30的peopleList.remove_if(IsOlderThan30);// 打印排序后的列表for (const auto& person : peopleList) {std::cout << person.name << " - " << person.age << std::endl;}system("pause");return 0;
}

8.C++11引入的std::forward_list

要使用它,需要添加头文件<forward_list>,用法和list很像,但由于是一种单向链表,所以只能沿一个方向移动迭代器,所以插入只能使用push_front(),基本操作如下:

#include <iostream>
#include <forward_list>int main() {std::forward_list<int> flist = {1, 2, 3, 4, 5};// 在头部插入一个新元素flist.push_front(0);// 删除头部元素flist.pop_front();// 遍历 forward_list 并打印每个元素for (int num : flist) {std::cout << num << " ";}std::cout << std::endl;system("pause");return 0;
}

引入std::forward_list 设计旨在解决一些 std::list(双向链表)的局限性,并提供一些特定的性能优势

  1. 性能优化:std::list 中,每个元素都需要存储两个指针(指向前一个和后一个元素),而 std::forward_list 中的每个元素只需要存储一个指向下一个元素的指针。这减少了内存的使用,并且可能提高缓存局部性,从而提升性能。
  2. 头部和尾部操作的效率: std::forward_list 提供了与 std::list 相似的高效头部和尾部插入与删除操作,但因为只维护单向链接,可能在某些实现中提供更优的性能。
  3. 编译器优化: 单向链表的结构可能使得编译器更容易进行某些优化,尤其是在内存对齐和迭代器实现方面。

这篇关于《21天学通C++》(第十八章)STL list和forward_list的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/967757

相关文章

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

C++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

C++ vector越界问题的完整解决方案

《C++vector越界问题的完整解决方案》在C++开发中,std::vector作为最常用的动态数组容器,其便捷性与性能优势使其成为处理可变长度数据的首选,然而,数组越界访问始终是威胁程序稳定性的... 目录引言一、vector越界的底层原理与危害1.1 越界访问的本质原因1.2 越界访问的实际危害二、基

Java List 使用举例(从入门到精通)

《JavaList使用举例(从入门到精通)》本文系统讲解JavaList,涵盖基础概念、核心特性、常用实现(如ArrayList、LinkedList)及性能对比,介绍创建、操作、遍历方法,结合实... 目录一、List 基础概念1.1 什么是 List?1.2 List 的核心特性1.3 List 家族成

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

C++归并排序代码实现示例代码

《C++归并排序代码实现示例代码》归并排序将待排序数组分成两个子数组,分别对这两个子数组进行排序,然后将排序好的子数组合并,得到排序后的数组,:本文主要介绍C++归并排序代码实现的相关资料,需要的... 目录1 算法核心思想2 代码实现3 算法时间复杂度1 算法核心思想归并排序是一种高效的排序方式,需要用

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么