温馨提示×

ubuntu c++怎么用 STL

小樊
50
2026-09-08 09:53:24
栏目: 编程语言

在 Ubuntu 下使用 C++ 的 STL(Standard Template Library,标准模板库) 其实和使用普通 C++ 一样,因为 STL 是 C++ 标准的一部分,只要用 g++ 编译即可。

下面从 环境准备 → 基本用法 → 常见 STL 示例 → 编译运行 给你一个完整说明。


一、Ubuntu 下准备 C++ 环境

1. 安装 g++

sudo apt update
sudo apt install g++ build-essential

2. 检查版本

g++ --version

二、STL 是什么(简单理解)

STL 主要包括:

  • 容器(Containers)
    • vector, list, map, set, unordered_map
  • 算法(Algorithms)
    • sort, find, count
  • 迭代器(Iterators)
  • 函数对象(Functors)

三、最简单的 STL 示例(vector)

示例:vector 使用

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> v = {3, 1, 4, 1, 5};

    v.push_back(9);

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

    return 0;
}

编译运行

g++ test.cpp -o test
./test

四、常用 STL 容器示例

1. map(键值对)

#include <iostream>
#include <map>

using namespace std;

int main() {
    map<string, int> m;
    m["apple"] = 3;
    m["banana"] = 5;

    for (auto &p : m) {
        cout << p.first << ": " << p.second << endl;
    }
}

2. set(去重有序)

#include <iostream>
#include <set>

using namespace std;

int main() {
    set<int> s = {3, 1, 2, 2, 3};
    for (int x : s) {
        cout << x << " ";
    }
}

3. unordered_map(哈希表,更快)

#include <iostream>
#include <unordered_map>

using namespace std;

int main() {
    unordered_map<string, int> um;
    um["a"] = 1;
    um["b"] = 2;
}

五、STL 算法示例

sort

#include <algorithm>
#include <vector>

vector<int> v = {5, 2, 9, 1};
sort(v.begin(), v.end());

find

auto it = find(v.begin(), v.end(), 9);
if (it != v.end()) {
    cout << "found";
}

六、C++11 / C++17 推荐写法(Ubuntu 默认支持)

编译时建议加标准:

g++ test.cpp -std=c++17 -o test

七、学习 STL 推荐路线

  1. vector(最常用)
  2. string
  3. map / unordered_map
  4. set
  5. algorithm(sort / find)
  6. 迭代器、lambda

如果你愿意,我可以:

  • 给你 STL 速查表
  • vector vs list 区别
  • 面试常考 STL 题
  • 结合 Ubuntu + Makefile / CMake

你想从哪一块继续?

0