📜  C++中STL组件的重要功能(1)

📅  最后修改于: 2023-12-03 14:59:49.812000             🧑  作者: Mango

C++中STL组件的重要功能

STL(标准模板库)是C++中的一个重要组件,它提供了丰富的数据结构和算法,可以大大提高程序员的开发效率。下面介绍一些STL的重要功能。

容器

容器是STL中的一种数据结构,常用的容器有vector、list、set和map等。它们都有自己的特点和适用场景,可以满足不同的需求。

vector

vector是一个动态数组,可以自动扩容。其中的元素是连续存储的,可以通过下标直接访问。vector在尾部插入和删除元素的时间复杂度为O(1),在其他位置插入和删除元素的时间复杂度为O(n)。

#include <vector>
using namespace std;

vector<int> v = {1, 2, 3, 4};
v.push_back(5); // 在尾部插入元素
v.pop_back(); // 在尾部删除元素
v.insert(v.begin() + 2, 6); // 在第三个位置插入元素
v.erase(v.begin() + 1); // 删除第二个元素
list

list是一个双向链表,可以快速地在任意位置插入或删除元素。list中的元素是不连续的,不能通过下标直接访问。

#include <list>
using namespace std;

list<int> l = {1, 2, 3, 4};
l.push_back(5); // 在尾部插入元素
l.pop_back(); // 在尾部删除元素
l.insert(next(l.begin(), 2), 6); // 在第三个位置插入元素
l.erase(next(l.begin(), 1)); // 删除第二个元素
set

set是一个有序集合,其中的元素是唯一的。set使用红黑树来实现,可以快速地进行增删改查操作。

#include <set>
using namespace std;

set<int> s = {4, 5, 1, 3, 2};
s.insert(6); // 插入元素
s.erase(3); // 删除元素
auto it = s.find(2);
if (it != s.end()) {
    // 找到元素
}
map

map是一个键值对的集合,其中的键是唯一的。map使用红黑树来实现,可以快速地进行增删改查操作。

#include <map>
using namespace std;

map<string, int> m = {{"Tom", 18}, {"Jerry", 20}};
m["Bob"] = 22; // 插入元素
m.erase("Jerry"); // 删除元素
auto it = m.find("Tom");
if (it != m.end()) {
    // 找到元素
    int age = it->second;
}
算法

STL中提供了许多常用算法,包括排序、查找、拷贝、求和等。这些算法可以大大简化代码,提高开发效率。

排序

STL中提供了多种排序算法,包括快速排序、归并排序等。可以对容器中的元素进行排序,也可以对数组进行排序。

#include <algorithm>
using namespace std;

vector<int> v = {4, 2, 5, 1, 3};
sort(v.begin(), v.end()); // 对vector进行排序
int a[] = {4, 2, 5, 1, 3};
sort(a, a + 5); // 对数组进行排序
查找

STL中提供了多种查找算法,包括二分查找、顺序查找等。可以在容器中查找指定元素,也可以在数组中查找指定元素。

#include <algorithm>
using namespace std;

vector<int> v = {4, 2, 5, 1, 3};
auto it = find(v.begin(), v.end(), 3); // 在vector中查找元素
int a[] = {4, 2, 5, 1, 3};
auto p = find(a, a + 5, 3); // 在数组中查找元素
拷贝

STL中提供了拷贝算法,可以将容器中的元素拷贝到另一个容器中。

#include <algorithm>
using namespace std;

vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2(5);
copy(v1.begin(), v1.end(), v2.begin()); // 将v1中的元素拷贝到v2中
求和

STL中提供了accumulate算法,可以求容器中的元素的和。

#include <numeric>
using namespace std;

vector<int> v = {1, 2, 3, 4, 5};
int sum = accumulate(v.begin(), v.end(), 0); // 求和
总结

STL提供了丰富的容器和算法,可以大大提高程序员的开发效率。要熟练掌握STL中各个组件的特点和用法,才能更好地发挥它的作用。