STL容器用法

· · 算法·理论

STL(标准模板库)提供了多种容器,用于存储和管理数据。以下是常用容器的用法总结,包括头文件、主要特性和常用操作。

1. 序列容器(顺序存储)

vector(动态数组)

list(双向链表)

deque(双端队列)

2. 关联容器(基于键值)

map(有序键值对)

set(有序集合)

unordered_map(哈希表,无序键值对)

unordered_set(无序集合)

3. 容器适配器(基于底层容器)

stack(栈)

queue(队列)

priority_queue(优先队列,最大堆)

4. 通用迭代器操作

示例:综合应用

#include <iostream>
#include <vector>
#include <map>
#include <set>
using namespace std;

int main() {
    vector<int> v = {3,1,4,1,5};
    sort(v.begin(), v.end()); // 1,1,3,4,5

    map<string, int> score;
    score["Alice"] = 90;
    score["Bob"] = 85;
    for (auto &p : score)
        cout << p.first << ": " << p.second << endl;

    set<int> s = {2,4,6};
    s.insert(3);
    if (s.find(4) != s.end()) cout << "4 exists";
    return 0;
}

选择建议

更多详细信息可查阅 cppreference.com。