温馨提示×

linux c++怎么用stl容器

小樊
33
2026-09-23 09:15:22
栏目: 编程语言

在 Linux 下用 C++ 使用 STL(Standard Template Library)容器,和你用哪个操作系统关系不大,主要是 C++ 标准库 的使用。下面给你一个实用、偏工程的介绍。


一、基本环境(Linux)

一般 Linux 自带 g++

g++ --version

编译 C++ 程序:

g++ main.cpp -std=c++17 -o app
./app

二、常见 STL 容器分类

1️⃣ 顺序容器(线性结构)

容器 特点
vector 动态数组,最常用
deque 双端队列
list 双向链表
array 固定大小数组(C++11)

2️⃣ 关联容器(自动排序)

容器 特点
set 不重复,有序
map key-value,有序
multiset 可重复
multimap key 可重复

3️⃣ 无序关联容器(哈希)

容器 特点
unordered_set 哈希集合
unordered_map 哈希表

4️⃣ 容器适配器

容器 特点
stack
queue 队列
priority_queue 优先队列

三、vector(最常用)

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> v;
    v.push_back(10);
    v.push_back(20);

    for (int x : v) {
        cout << x << " ";
    }
    cout << endl;

    cout << v[0] << endl;
    cout << v.size() << endl;
}

四、map / unordered_map

map(有序)

#include <map>
#include <string>

map<string, int> m;
m["a"] = 1;
m["b"] = 2;

for (auto& [k, v] : m) {
    cout << k << ": " << v << endl;
}

unordered_map(更快)

#include <unordered_map>

unordered_map<string, int> um;
um["x"] = 100;

五、set / unordered_set

#include <set>

set<int> s = {3, 1, 2};
s.insert(4);

for (int x : s) {
    cout << x << " ";
}

六、遍历方式(推荐)

vector<int> v = {1, 2, 3};

// C++11 以后
for (auto x : v) {}

// 需要修改
for (auto& x : v) {}

// 索引
for (size_t i = 0; i < v.size(); ++i) {}

七、常见坑(Linux C++ 特别要注意)

1️⃣ 迭代器失效

vector<int> v = {1,2,3};
for (auto it = v.begin(); it != v.end(); ) {
    if (*it == 2)
        it = v.erase(it);
    else
        ++it;
}

2️⃣ 用 size_t 而不是 int

for (size_t i = 0; i < v.size(); ++i)

3️⃣ 传入大对象用引用

void f(const vector<int>& v);

八、推荐学习顺序

  1. vector
  2. map / unordered_map
  3. set
  4. list / deque
  5. algorithmsort, find

如果你愿意,可以告诉我:

  • 你是 初学者 / 有一定基础
  • 用在 服务器 / 算法 / 嵌入式
  • 想看 例子 / 源码结构 / 性能对比

我可以直接给你对应场景的 STL 用法。

0