【C++】STL的基本用法

简介: 【C++】STL的基本用法



🌍1. STL概念

C++中的STL是指标准模板库的缩写。STL提供了一组通用的模板类和函数,用于实现常见的数据结构和算法,如向量(vector)、链表(list)、栈(stack)、队列(queue)、映射(map)等,以及包括排序、搜索、算法等在内的各种算法操作。

✨1.1 常见容器

  1. vector:动态数组,支持快速随机访问。
  2. list:双向链表,支持高效插入和删除操作。
  3. stack:栈,后进先出(LIFO)数据结构。
  4. queue:队列,先进先出(FIFO)数据结构。
  5. map:映射,键-值对的关联容器。

✨1.2 六大组件

  1. 容器(Containers):容器是STL的核心组件之一,提供了各种数据结构,如向量(vector)、链表(list)、双端队列(deque)、栈(stack)、队列(queue)、映射(map)等。容器用于存储和组织数据,不同类型的容器适用于不同的数据访问和操作需求。
  2. 算法(Algorithms):STL包含了一系列通用算法,用于操作容器中的数据,例如排序、查找、复制、变换等。这些算法是高度优化的,可适用于不同类型的容器,使开发人员能够更轻松地进行常见操作。
  3. 迭代器(Iterators):迭代器是用于访问容器中元素的通用接口。它们提供了统一的方法来遍历容器,并使算法能够与不同类型的容器一起使用,而不需要了解底层容器的细节。
  4. 仿函数(Function Objects):仿函数是可调用对象,它们在STL中用于执行特定操作,如排序或变换。STL提供了一些内置的仿函数,同时也允许开发人员定义自己的仿函数,以满足特定需求。
  5. 适配器(Adapters):适配器是用于修改或扩展容器和迭代器行为的组件。STL中包括一些适配器,如栈适配器(stack adapter)和队列适配器(queue adapter),它们基于其他容器提供了不同的接口。
  6. 配置器(Allocators):配置器用于管理内存分配和释放,以支持容器的底层数据结构。STL提供了默认的配置器,同时也允许开发人员自定义配置器以满足特定的内存管理需求。

🌍2.  STL容器之vector

✨2.1 vector

vector 是 C++ 标准库提供的一个动态数组容器,它可以自动扩展和收缩,使其非常适合存储和管理可变数量的元素。

传参

  1. 值传递
  2. 引用传递
  3. 指针传递

1. 值传递,调用Disp(v);

void Disp(vector<int> v){//值传递,不会修改原值
    for(int value:v){
        cout<<value<<" ";
    }
    cout<<endl;
    v.erase(v.begin()+1);
}

2. 引用类型,调用Disp(v);

void Disp(vector<int> &v){//引用传递,修改形参也会修改实参
    for(int value:v){
        cout<<value<<" ";
    }
    cout<<endl;
    v.erase(v.begin()+1);
}

3. 指针传递,调用Disp(&v);

void Disp(vector<int> *v){//指针传递,修改形参也会修改实参
    for(int value : *v){
        cout << value << " ";
    }
    cout << endl;
    v->erase(v->begin() + 1);
}

✨2.2 基本用法示例

2.1 包含头文件

#include <vector>

2.2 创建一个空的vector

vector<int> myVector;

2.3 向vector 中添加元素

在使用 cin >> myVector[i]; 时,由于 myVector 是一个空的向量,尝试访问 myVector[i] 可能导致未定义的行为。因为在 for 循环中,你试图直接通过下标将输入的值存储到 myVector 中,但是 myVector 的大小为零,因此没有有效的索引。这可能导致程序崩溃或产生不可预测的结果。

myVector.push_back(42);
myVector.push_back(23);
myVector.push_back(17);
//输出:42 23 17
//错误示例
for(int i=0;i<n;i++){
    cin>>myVector[i];
}
//解决
for(int i=0;i<n;i++){
    int k;
    cin>>k;
    myVector.push_back(k);
}

2.4 访问 vector 中的元素

int firstElement = myVector[0];
int secondElement = myVector[1];

2.5 获取 vector 的大小

int size = myVector.size();

2.6 遍历元素

//遍历方式一
for (int i = 0; i < myVector.size(); i++) {
    cout << myVector[i] << " ";
}
//遍历方式二
for (int value : myVector) {
    cout << value << " ";
}

2.7 插入元素到指定位置

myVector.insert(myVector.begin() + 1, 100);  // 在myVertor[1]插入值为100的元素

2.8 删除元素

注意:循环删除可能导致迭代器失效,可以使用范围删除。

myVector.erase(myVector.begin() + 1);  // 删除元素myVertor[1]
myVector.erase(myVector.begin() + m,myVector.end()); //删除v[m]~v[size-1]
/*错误示例*/
//去除nums1[m]后的元素
for(int i=m;i<nums1.size();i++){  //循环删除导致迭代器失效
    nums1.erase(nums1.begin()+i);
}
/*正确示例*/
nums1.erase(nums1.begin()+m,nums1.end());

2.9 清空 vector

myVector.clear();

2.10 示例程序

创建了一个 vector,向其中添加、插入、删除元素,并最后清空了vector

#include <iostream>
#include <vector>
using namespace std;
void Disp(vector<int> &v){
    //输出方式一
    for(int value : v){
        cout << value << " ";
    }
    cout << endl;
    //输出方式二
    /*
    for(int i=0;i<v.size();i++){
        cout<<v[i]<<" ";
    }
    cout<<endl;
    */
}
int main(){
    //定义
    vector<int> v;
    //添加元素
    v.push_back(42);
    v.push_back(12);
    v.push_back(27);
    Disp(v);
    //释放元素
    v.erase(v.begin()+1);
    Disp(v);
    //插入元素
    v.insert(v.begin()+1,12);
    Disp(v);
    //size()大小
    cout<<v.size()<<endl;
    //删除
    //部分删除
    v.erase(v.begin(),v.end());
    //全部删除
    //v.clear();
    cout<<v.size()<<endl;
    return 0;
}

2.3 vector 的简化版源码示例

该简化的 MyVector 类模拟了 vector 的基本功能,包括动态数组的管理、元素的添加、访问和扩容等。

#include <iostream>
#include <stdexcept>
using namespace std;
template <typename T>
class MyVector {
private:
    T* data;        // 存储元素的数组
    size_t size;    // 当前元素数量
    size_t capacity; // 数组容量
public:
    // 构造函数
    MyVector() : data(nullptr), size(0), capacity(0) {}
    // 析构函数
    ~MyVector() {
        delete[] data; // 释放内存
    }
    // 返回元素数量
    size_t Size() const {
        return size;
    }
    // 添加元素到尾部
    void PushBack(const T& value) {
        if (size == capacity) {
            // 如果容量不足,扩展数组
            if (capacity == 0) {
                capacity = 1; // 初始容量为1
            } else {
                capacity *= 2; // 容量翻倍
            }
            T* newData = new T[capacity];
            for (size_t i = 0; i < size; ++i) {
                newData[i] = data[i];
            }
            delete[] data;
            data = newData;
        }
        data[size] = value; // 添加元素
        size++;
    }
    // 访问元素
    T& operator[](size_t index) {
        if (index < size) {
            return data[index];
        } else {
            throw out_of_range("Index out of range");
        }
    }
};
int main() {
    MyVector<int> myVector;
    myVector.PushBack(42);
    myVector.PushBack(23);
    myVector.PushBack(17);
    for (size_t i = 0; i < myVector.Size(); i++) {
        cout << myVector[i] << " ";
    }
    return 0;
}

🌍3. STL容器之map

✨3.1 map

在C++的STL(标准模板库)中,map是一种关联式容器,用于存储键-值对。它按照键的顺序进行排序,并且具有快速查找功能。


✨3.2 基本用法示例

1. 包含头文件

#include <map>

2. 创建一个空的map

map<string, int> myMap;

3. 向 map 中插入键值对

myMap["Alice"] = 25;
myMap["Bob"] = 30;
myMap["Charlie"] = 35;

4. 访问 map 中的值

int age = myMap["Alice"];

5. 遍历输出

// 输出
for (auto it = myMap.begin(); it != myMap.end(); it++) {
    cout << it->first << ":" << it->second << endl;
}
// 使用迭代器遍历 map 中的键值对
for (const auto& pair : myMap) {
    cout << "Name: " << pair.first << ", Age: " << pair.second << endl;
}

6. 检查 map 中是否包含特定的键

if (myMap.find("Alice") != myMap.end()) {
    cout << "Alice is in the map." << endl;
}

7. 示例程序示例程序创建了一个 map,向其中添加键值对,访问键值对的值,并检查特定的键是否存在。

#include <iostream>
#include <map>
using namespace std;
void Disp(map<string,int> &m){
    //输出方式一
    for(auto it=m.begin();it!=m.end();it++){
        cout<<it->first<<" : "<<it->second<<endl;
    }
    //输出方式二
    /*
    for(const auto &p:m){
        cout<<p.first<<" : "<<p.second<<endl;
    }
    */
}
int main(){
    //定义
    map <string,int> m;
    //创建
    m["Alice"]=42;
    m["Ella"]=24;
    m["ackac"]=15;
    Disp(m);
    //查找相应值
    //没找到对应元素则返回m.end(),若该元素处在末尾则它的下个元素是m.end()
    if (m.find("Alice") != m.end()) {
        cout << "Alice is in the map." << endl;
    }
    else{
        cout << "Alice is't in the map." << endl;
    }
    //访问对应值
    int k=m["Alice"];
    cout<<k<<endl;
    return 0;
}

✨3.3 map的简化版源码示例

map 是 C++ 标准库提供的关联容器,它实际上是一个基于红黑树的有序关联容器,用于存储键值对,并能够按键的排序顺序进行访问。这个简化的 MyMap 类模拟了 map 的一些基本功能,包括插入和查找键值对。在实际的 map 实现中,还包括了红黑树平衡操作等,以确保高效的键值对查找和维护有序性。

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
    // 创建一个空的 map,用于存储名字和年龄的关联关系
    map<string, int> myMap;
    // 向 map 中插入键值对
    myMap["Alice"] = 25;
    myMap["Bob"] = 30;
    myMap["Charlie"] = 35;
    // 使用迭代器遍历 map 中的键值对
    for (const auto& pair : myMap) {
        cout << "Name: " << pair.first << ", Age: " << pair.second << endl;
    }
    // 访问特定键的值
    int age = myMap["Alice"];
    cout << "Alice's age is " << age << endl;
    // 检查特定键是否存在于 map 中
    if (myMap.find("Alice") != myMap.end()) {
        cout << "Alice is in the map." << endl;
    }
    return 0;
}

🌍4. STL容器之set

✨4.1 set

setC++标准模板库[STL]中的一个关联容器,它提供了一种有序的、不重复的集合set使用红黑树实现,这使得它的插入、删除和查找操作都具有较好的性能。

以下是set的一些关键特点:

  1. 有序性:set中的元素是按照严格的弱顺序排列的。默认情况下,元素按升序排序,但可以通过提供自定义的比较函数来实现不同的排序方式。
  2. 唯一性:set中不允许重复的元素,每个元素在集合中只能出现一次。
  3. 动态操作:set支持插入和删除操作,可以在运行时动态地改变集合的大小。
  4. 快速查找: 由于底层实现采用了红黑树,set提供了快速的查找操作。查找的平均复杂度是O(log n)。

✨4.2 基本用法示例

2.1 包含头文件

#include <set>

2.2 创建一个空的 set

set<int> mySet;

2.3 向 set 中添加元素

没有mySet[i],不能像使用数组或类似容器(如vector)那样使用索引访问元素。set是基于红黑树实现的关联容器,它不提供通过索引直接访问元素的功能。因此,使用mySet[1]这样的语法会导致编译错误。

// 插入元素
mySet.insert(10);
mySet.insert(5);
mySet.insert(20);
mySet.insert(15);
//默认升序 5 10 15 20
set<int> mySet = {50,10,20,30,40};
//存储还是{10,20,30,40,50}

2.4 获取 set的大小

int size = mySet.size();

2.5 遍历元素

/*遍历方式*/
//遍历
for(int value :mySet){
   cout<<value<<" ";
}
cout<<endl;
// 使用迭代器遍历set中的元素
for (auto it = mySet.begin(); it != mySet.end(); it++) {
    cout << " " << *it;
}
cout << endl;
// 使用范围-based for 遍历
for (const auto& element : mySet) {
    cout << " " << element;
}
cout << endl;

2.6 删除元素

set不支持通过迭代器的算术运算进行定位和删除元素。因为 set 是一个关联容器,它的元素是按照某种比较准则有序排列的,而不是按照它们在容器中的物理位置排列的。

mySet.erase(15);//删除值为15的元素
//mySet.erase(mySet.begin()+1); is error!

2.7 查找find()

返回值:

  • 如果找到元素,返回指向该元素的迭代器。
  • 如果未找到元素,返回容器的 end 迭代器。

注意:如果找到的元素在最后一个,返回的则不是end迭代器!

#include <iostream>
#include <set>
using namespace std;
int main() {
    set<int> mySet = {50,10,20,30,40};
    // 使用 find 查找元素
    set<int>::iterator it = mySet.find(30);//返回的是迭代器对象,未找到则返回mySet.end()
    // 检查是否找到
    if (it != mySet.end()) {
        cout << "元素 30 找到了,位置是:" << distance(mySet.begin(), it) << endl;
    } else {
        cout << "元素 30 未找到。" << endl;
    }
    return 0;
}
/*输出:
元素 30 找到了,位置是:2
*/

2.8 清空 set

mySet.clear();

2.9 示例程序

#include <iostream>
#include <set>
using namespace std;
void Disp(set<int> s){
    //遍历方式一
    for(int value:s){
        cout<<value<<" ";
    }
    cout<<endl;
    //遍历方式二
    /*
    for (auto it = s.begin(); it != s.end(); it++) {
        cout<< *it << " ";
    }
    cout << endl;
    //遍历方式三
    for (const auto& it : s) {
        cout<< it << " ";
    }
    cout << endl;
    */
}
int main(){
    //定义
    set <int> s;
    //插入
    s.insert(42);
    s.insert(24);
    s.insert(12);
    Disp(s);
    //再次定义,原来的值被删除
    s={4,11,22,33,55,66,77};
    Disp(s);
    //输出
    s.erase(4);
    Disp(s);
    //size()
    cout<<s.size()<<endl;
    //查找
    set<int>::iterator it = s.find(30);//返回的是迭代器对象,未找到则返回mySet.end()
    if (it != s.end()) {
        cout << "元素 30 找到了,位置是:" << distance(s.begin(), it) << endl;
    } 
    else {
        cout << "元素 30 未找到。" << endl;
    }
    //清空
    s.clear();
    cout<<s.size()<<endl;
    return 0;
}

目录
相关文章
|
1天前
|
C++ 容器
C++ STL标准库 《map容器详解》
C++ STL标准库 《map容器详解》
7 0
|
1天前
|
存储 C++ 容器
C++ STL标准库 《map容器详解》
C++ STL标准库 《map容器详解》
7 0
|
1天前
|
算法 搜索推荐 C++
C++之STL常用算法(遍历、查找、排序、拷贝、替换、算数生成、集合)
C++之STL常用算法(遍历、查找、排序、拷贝、替换、算数生成、集合)
10 0
|
2天前
|
编译器 C语言 C++
C++ STL中list迭代器的实现
C++ STL中list迭代器的实现
C++ STL中list迭代器的实现
|
2天前
|
C++
【C++航海王:追寻罗杰的编程之路】STL—next_permutation函数
【C++航海王:追寻罗杰的编程之路】STL—next_permutation函数
4 0
|
3天前
|
设计模式 存储 C++
【C++/STL】:stack/queue的使用及底层剖析&&双端队列&&容器适配器
【C++/STL】:stack/queue的使用及底层剖析&&双端队列&&容器适配器
25 2
|
3天前
|
编译器 C++ 容器
【C++/STL】:list容器的深度剖析及模拟实现
【C++/STL】:list容器的深度剖析及模拟实现
9 2
|
3天前
|
存储 C++ 容器
【C++/STL】:list容器的基本使用
【C++/STL】:list容器的基本使用
9 1
|
3天前
|
算法 编译器 Linux
【C++/STL】:vector容器的底层剖析&&迭代器失效&&隐藏的浅拷贝
【C++/STL】:vector容器的底层剖析&&迭代器失效&&隐藏的浅拷贝
6 0
|
3天前
|
存储 算法 C++
【C++/STL】:vector容器的基本使用
【C++/STL】:vector容器的基本使用
14 1